当我执行此代码时,它会生成算术散度,或者不会生成非常接近的 float ,当数字采用 2**n-p/q 形式时,就会发生算术散度,可以产生可接受的结果,有时会产生非常快的散度。我已经阅读了一些有关浮点算术的文档,但我认为问题在其他地方,但在哪里?如果有人有想法,我会很高兴了解此事......
我尝试在 Python 3.4.5(32 位)上执行代码,并使用 repl.it 和 trinket 在线尝试 url[ https://trinket.io/python3/d3f3655168]结果相似。
#this code illustrates arithmetical divergence with floating point numbers
# on Python 3.4 an 3.6.6
def ErrL(r):
s=1
L=[]
for k in range(10):
s=s*(r+1)-r
L.append(s)
return L
print(ErrL(2**11-2/3.0)) # this number generate a fast divergence in loop for
#[0.9999999999997726, 0.9999999995341113, 0.9999990457047261, 0.9980452851802966, -3.003907522359441, -8200.33724163292, -16799071.44994476, -34410100067.30351, -70483354973240.67, -1.4437340543685667e+17]
print(ErrL(2**12-1/3.0)) # this number generate a fast divergence in loop for
#[0.9999999999995453, 0.9999999981369001, 0.9999923674999991, 0.968732191662184, -127.09378815725313, -524756.5521508802, -2149756770.9781055, -8806836909202.637, -3.607867520470422e+16, -1.4780230608860496e+20]
print(ErrL(2**12-1/10.0)) # this number generate a fast divergence in loop for
#[0.9999999999995453, 0.9999999981369001, 0.9999923670652606, 0.9687286296662023, -127.11567712053602, -524876.117595124, -2150369062.0754633, -8809847014512.865, -3.609306223376185e+16, -1.478696666654989e+20]
print(ErrL(2**12-1/9.0)) # no problem here
#[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
print(ErrL(2**12-1/11.0)) # no problem here
#[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
我期望的显然是一个十个向量!
最佳答案
使用 Python 2 执行此代码时,整数之间的 /
表示整数除法(现在在 Python 3 中称为 //
)。
所以,在这种情况下,2/3
、1/3
等都等于0,你得到的是ErrL(2 **11)
,...,始终为 1。
在 Python 3 中,2/3
是 float ,而不是 0,这解释了为什么会得到不同的结果。
关于python - 为什么一些非常接近的 float 会导致 3.4.x 到至少 3.6.6 版本的 Python 代码出现如此大的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55423587/