return should be in place of break, I think. Also rounding to 2 decimals does not make sense after so small tolerance for error, generally you also do not round, you just format the printing.
pyTony
pyMod
6,330 posts since Apr 2010
Reputation Points: 879
Solved Threads: 989
Skill Endorsements: 27
line 15
return estimate
should be outside the loop
sneekula
Nearly a Posting Maven
2,483 posts since Oct 2006
Reputation Points: 1,000
Solved Threads: 231
Skill Endorsements: 2
I would write the code like this ...
def newton_approx(x):
"""
Newton's method to get the square root of x
using successive approximations
"""
tolerance = 0.000001
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
return estimate
# test
x = 2
print("newton = %0.15f" % newton_approx(x))
print("x**0.5 = %0.15f" % (x**0.5))
'''
newton = 1.414213562374690
x**0.5 = 1.414213562373095
'''
vegaseat
DaniWeb's Hypocrite
6,499 posts since Oct 2004
Reputation Points: 1,451
Solved Threads: 1,618
Skill Endorsements: 37
Question Answered as of 6 Months Ago by
vegaseat,
sneekula
and
pyTony I would add parameter for current difference and return value from function which reaches the level of tolerance (which also could be a parameter).
pyTony
pyMod
6,330 posts since Apr 2010
Reputation Points: 879
Solved Threads: 989
Skill Endorsements: 27