我使用以下代码计算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在不同的地方进行舍入。有人怎么知道在危急情况下哪一个更好?例如,为PHD论文编写需要高度物理精度的数学方程的朋友?
答案 0 :(得分:3)
您可以使用decimal
模块达到这种准确度:
>>> import decimal
>>> decimal.getcontext().precision = 15
>>> decimal.Decimal(33).sqrt()
Decimal('5.744562646538028659850611468')
关于浮点不准确:http://docs.python.org/2/tutorial/floatingpoint.html
答案 1 :(得分:3)
Python和Excel都使用双精度浮点,精度取决于底层C库,它通常使用硬件浮点单元。通用FPU实现了IEEE-754双。
话虽如此,我怀疑你正在使用print
语句进行格式化。请参阅下面的差异。
>>> import math
>>> math.sqrt(33)
5.744562646538029
>>> print math.sqrt(33)
5.74456264654
答案 2 :(得分:1)
这取决于实施。
如果要使用内置模块,请使用decimal
模块。
一些外部模块如:
mpmath:http://code.google.com/p/mpmath/
bigfloat:http://pythonhosted.org/bigfloat/
也很好。