<p>你正在失去精确性。这是因为Python中的<code>float</code>实现了<code>double floating point</code>精度,它只能保证精度达到15/16位。你知道吗</p>
<p>当您这样做时:</p>
<pre><code>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
</code></pre>
<p>连续不断地,您正在突破精度限制,在<code>0.000001</code>中的最后一个<code>1</code>之后还有一些其他值,它仅表示为<code>0.000001</code>。这样就得到了累积误差。你知道吗</p>
<p>如果你将你的<code>variable</code>初始化为<code>0</code>,事情会有所不同。这是因为在计算中:</p>
<pre><code>0.000000 + 0.000001
0.000001 + 0.000001
0.000002 + 0.000001
#and so on
</code></pre>
<p>虽然<code>0.000001</code>的实际值并不完全是<code>0.000001</code>,但第16位的不精确性与有效数字相差甚远:</p>
<pre><code>0.000000 + 0.00000100000000000000011111
0.000001 + 0.00000100000000000000011111 #insignificant error
</code></pre>
<p>也可以使用<code>decimal</code>值而不是<code>double</code>来避免错误:</p>
<pre><code>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
</code></pre>