I used the following code to compute square root in Python:
from math import *
#find average of two numbers
def average(a, b):
print "the average is",(a + b) / 2.0,"\n"
return (a + b) / 2.0
#guess not good enouhgh
def improve(guess, x):
print "improved guess is ",average(guess, x/guess),"\n"
return average(guess, x/guess)
#As long as the guess is not good enough, keep on improving the guess
def good_enough(guess, x):
d = abs(guess*guess - x)
print d," is the currentguess\n"
return (d < 0.001)
#As long as the guess is not good enough, keep on improving the guess
def square_root(guess, x):
while(not good_enough(guess, x)):
guess = improve(guess, x)
print "current guess is ",guess,"\n"
return guess
if __name__ == "__main__":
x = square_root(5, 33)
print "final answer is",x
The result of the square root of 33 was :5.74456521739
I used the square root function in excel 2003:
=sqrt(33)
setting result at 15 decimal places and got the result:5.744562646538030
I then used:
math.sqrt(33)
from the standard Python 2.7.2 math library
and got the result: 5.74456264654
I then increased accuracy of my Program: return (d < 0.000001)
and got return 5.74456264654 the same as the my program
The question is why is Python rounding and Excel 2003 is rounding in different places. How can someone know which one is better to use in a critical situation? For example friends who are writing maths equations that need a high degree of accuracy in physics for a PHD thesis?