这是 Udacity 深度学习课程中的一个练习。
谁能解释为什么最终答案不是 1.0?
v1 = 1e9
v2 = 1e-6
for i in range(int(1e6)):
v1 = v1 + v2
print 'answer is', v1 - 1e9
# answer is 0.953674316406
这是 Udacity 深度学习课程中的一个练习。
谁能解释为什么最终答案不是 1.0?
v1 = 1e9
v2 = 1e-6
for i in range(int(1e6)):
v1 = v1 + v2
print 'answer is', v1 - 1e9
# answer is 0.953674316406
因为1e-6
不能完全表示为浮点值:
print("{:.75f}".format(1e-6))
'0.000000999999999999999954748111825886258685613938723690807819366455078125000'
如果您使用可以精确表示的数字,例如v2 = 1.0/(2**20)
并将迭代计数更改为2**20
您将得到0
. 然而,正如@user2357112 指出的那样,只有当所有中间结果都可以使用浮点值精确表示时,这个属性才成立。
查看 Python 教程以获取更多详细信息:https ://docs.python.org/3/tutorial/floatingpoint.html
让我们检查一下在浮点加法中v1
看到了什么:v2
>>> v3 = (v1+v2)-v1
>>> print "%.25f %.25f" % (v3,1e6*v3)
0.0000009536743164062500000 0.9536743164062500000000000
发生的情况是,除了前导之外的所有内容都1
从 的二进制尾数中移出,1e-6
同时使指数与 相等1e9
。这意味着最终值是10**6 * 2**(-20) = (1.024)**(-2)
,它准确地给出了观察值
>>> print "%.17f" % (1.024)**(-2)
0.95367431640625000