Python的Excel浮点差异很大
我使用下面的代码来计算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.2math库
得出结果: 5.74456264654
然后我增加了我的程序的准确性:return(d <0.000001)
并得到回报5.74456264654与我的程序相同
问题是为什么Python四舍五入和Excel 2003四舍五入在不同的地方。 一个人如何知道在危急情况下哪一个更好? 例如,正在编写math方程式的朋友需要物理学方面的高度精确度来完成博士论文?
Python和Excel都使用双精度浮点,精度取决于底层C库,通常使用硬件浮点单位。 常见的FPU实现IEEE-754双。
话虽如此,我怀疑你正在使用格式化的print
语句。 看到下面的区别。
>>> import math >>> math.sqrt(33) 5.744562646538029 >>> print math.sqrt(33) 5.74456264654
你可以使用decimal
模块来达到这个准确度:
>>> import decimal >>> decimal.getcontext().precision = 15 >>> decimal.Decimal(33).sqrt() Decimal('5.744562646538028659850611468')
关于浮点错误: http : //docs.python.org/2/tutorial/floatingpoint.html
这取决于实施。 如果你想使用inbuild模块,使用decimal
模块。 一些外部模块,如:
mpmath: http : //code.google.com/p/mpmath/
bigfloat: http ://pythonhosted.org/bigfloat/
也不错。