我使用以下代码在 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
33 的平方根的结果是:5.74456521739
我在 excel 2003 中使用了平方根函数:
=sqrt(33)
设置结果保留15位小数得到结果:5.744562646538030
然后我使用了:
math.sqrt(33)
来自标准 Python 2.7.2 数学库
得到结果:5.74456264654
然后我提高了程序的准确性:return (d < 0.000001)
得到返回5.74456264654和我的程序一样
问题是为什么Python四舍五入和Excel 2003在不同的地方四舍五入。一个人怎么知道在危急情况下使用哪个更好?比如正在写数学方程式的 friend ,需要在物理上对PHD论文有很高的准确度?
请您参考如下方法:
Python 和Excel 都使用 double float ,精度取决于底层C 库,通常使用硬件浮点单元。普通 FPU 实现 IEEE-754 double。
话虽如此,我怀疑您正在使用执行格式设置的 print 语句。请参阅下面的差异。
>>> import math
>>> math.sqrt(33)
5.744562646538029
>>> print math.sqrt(33)
5.74456264654
