PROGRAMMING

m9/ PYTHON REMEMBERS

Last update:   25-07-2021

Approximate

p126 ! Loops are ofthen used by starting with an approximate and improving it. For example, one way of computing square is with Newton's method. $\sqrt{4} = 2$

# Start with any estimate and then compute a better estimation ...
# with formula: y = (x + a/x) / 2

# For example is a = 4, x = 3
# the result is preatty close to correct answer

a = 4; x =10

while True:
y = (x + a/x) / 2
print(y)
if (y == x):
break
x = y

print(y)

# 5.2
# 2.9846153846153847
# 2.1624107850911973
# 2.006099040777959
# 2.00000927130158
# 2.000000000021489
# 2.0
# 2.0
# 2.0
... 15 lines 
p128 In general it is dangerous to test float equality. It is better to compute the absolute value of difference between them.

a = 64; x =10

epsilon = 0.0000001 # how close is close enought

while True:

y = (x + a/x) / 2
print(y)

if abs(y - x) < epsilon:
break
x = y

print(y)

# 8.2
# 8.002439024390243
# 8.000000371689179
# 8.000000000000009
# 8.0
# 8.0
... 9 lines 

Questions

A B C D E F
🔔
1/1