Given the .5 in avg_guess - do I need all the float(arg) specifications?
# Heron of Alexandria method for approximating
# the square root of a number
def heron(num, guess, tolerance):
print "Your guess squared:",guess**2
if guess**2 != num:
print "When squared, the guess:", guess, "is",abs(float(num) - float(guess)**2), "away from", num, "\n"
if abs(float(num) - float(guess)**2) > float(tolerance):
avg_guess = 0.5 * (float(guess) + (float(num) / float(guess)))
return heron(num, avg_guess, tolerance)
print "Given your tolerance, this is Heron's best guess:", guess, "\n"
else:
print guess, "is correct!\n"
I noticed that to a certain tolerance, this function will return 5.0 as the answer... Not sure why?
heron(25, 3, .00000001)
returns 5.0 from the "else:" condition, but
heron(25, 3, .0000001)
terminates from the tolerance in the initial nested "if:" condition, printing: Given your tolerance, this is Heron's best guess: 5.00000000233.