当我执行这段代码时,它会产生算术发散,或者不是非常接近的浮点数,当数的形式为2时会发生,n-p/q会产生一个可接受的结果,有时会产生一个非常快的发散。我读过一些关于浮点运算的文档,但我认为问题在别处,但在哪里呢?如果有人有主意,我很乐意理解这件事。。。你知道吗
我曾尝试在python3.4.5(32位)上执行代码,并在网上试用过复制和韦小宝网址[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]
我所期望的显然是一个十个一的向量!你知道吗
在使用python2执行此代码时,整数之间的
/
表示整数除法(在python3中现在称为//
)。你知道吗所以,在这个例子中,
2/3
,1/3
等等都等于0,得到的是ErrL(2**11)
,…,总是1。你知道吗对于python3,
2/3
是一个float,而不是0,这解释了为什么会得到不同的结果。你知道吗发散很快的原因是数学。如果你写
f(s) = (r+1) * s - r
,很明显导数就是常数r+1
。根据wikipedia,iee754表示中的64位浮点数的尾数为53位。当r接近2**11
时,最后一位的错误将需要不到5个步骤才能接近1。当数字接近2**12
时,它在第5次迭代时爆炸,这就是你得到的结果。你知道吗呸,我40年前学的数学还没坏。。。你知道吗
相关问题 更多 >
编程相关推荐