您正在失去精确度。这是因为Python中的float
实现了double floating point
精度,这只能保证精度高达15/16位数字。
当你这样做:
1,000,000,000 + 0.000001
1,000,000,000.000001 + 0.000001
# and so on, note that you are adding the 16-th digit
# but 1,000,000,000.000001 is not actually exactly 1,000,000,000.000001
# behind is something like 1,000,000,000.000001014819 or 1,000,000,000.000000999819
不断,你破坏了精度的限制,也有在0.000001
最后1
其仅作为0.000001
代表经过一些其他值。因此你有累积的错误。
如果你将variable
初始化为0
,情况就会不同。这是因为在计算:
0.000000 + 0.000001
0.000001 + 0.000001
0.000002 + 0.000001
#and so on
虽然0.000001
的实际值是不完全0.000001
,但16个数字不精确远离显著号:
0.000000 + 0.00000100000000000000011111
0.000001 + 0.00000100000000000000011111 #insignificant error
你也可以避免错误使用decimal
值,而不是double
:
from decimal import *
variable = Decimal(1000000000)
addition = Decimal(1e-6)
for i in xrange(1000000):
variable = variable+ addition #0.000001
variable = variable-Decimal(1000000000) #1 subtracts with 1 billion again
variable
来源
2016-03-10 14:38:39
Ian
看起来像典型的浮点问题 - 计算机不能真正代表这些数字通过位,所以它变得“接近”,但你会得到一些错误和15或16位有效数字(小数点前9或10,小数点后6 )听起来符合C语言中的'float'(我通常粗略地谈论;我不知道具体情况,否则我会发布为答案,而不是评论)。 – dwanderson
此外,为什么这个标签为'performancecounter'?这似乎与“性能”没有任何关系,而与准确性有关。 – dwanderson
一些细节,以防止这个问题可以找到[这里](http://stackoverflow.com/questions/11522933/python-floatingpoint-arbitrary-precision-available)。 –