Python 中 math.pi 的精度
我在用Python编程的时候遇到了一个奇怪的错误:
import math
print(math.tan(math.pi/4) == 1)
结果显示为False,因为math.tan(math.pi / 4)的值是0.9999999999...
你知道为什么Python会出现这样的情况吗?我想知道除了精度问题之外,还有其他原因吗?
谢谢!
3 个回答
1
解决这个问题的一个好方法是实现一个自定义的函数叫做isEqual,这个函数会比较两个数字,并且允许有一个指定的误差范围(delta)。
DELTA = 0.0001
def isEqual(number1, number2)
if (number1 - DELTA) < number2 or (number1 + DELTA) > number2 # as example and demonstration of the idea
1
你会遇到精度错误,这一点很明显。不过,如果你想得到更准确的圆周率(Pi)的值,可以使用这个方法(也叫阿基米德的方法):
import math
# max error allowed
eps = 1e-10
# initialize w/ square
x = 4
y = 2*math.sqrt(2)
ctr = 0
while x-y > eps:
xnew = 2*x*y/(x+y)
y = math.sqrt(xnew*y)
x = xnew
ctr += 1
print("PI = " + str((x+y)/2))
print("# of iterations = " + str(ctr))
2
这是R语言常见问题解答第7.31条的Python版本:
http://www.hep.by/gnu/r-patched/r-faq/R-FAQ_82.html
在Python中的这个例子得到了相同的结果:
>>> a = math.sqrt(2)
>>> a*a - 2
4.440892098500626e-16
你提到的切线例子中的差别也非常非常小:
>>> math.tan(math.pi/4) - 1
-1.1102230246251565e-16
这个差别只是因为在进行四分之一的除法和计算角度的切线时,所有浮点运算累积起来的结果。