擅长:python、mysql、java
<blockquote>
<p>For relatively simple floats, the numerical precision is sufficient to represent them exactly.</p>
</blockquote>
<p>不,即使是简单的小数也不一定有准确的IEEE-754表示:</p>
<pre class="lang-py prettyprint-override"><code>>>> format(0.1, '.20f')
'0.10000000000000000555'
>>> format(0.2, '.20f')
'0.20000000000000001110'
>>> format(0.3, '.20f')
'0.29999999999999998890'
>>> format(0.1 + 0.2, '.20f')
'0.30000000000000004441'
</code></pre>
<p>2的幂(x.0,x.5,x.25,x.125,…)是精确表示的模精度问题。你知道吗</p>
<blockquote>
<p>Do the python standards guarantee a particular float will be "binned" into a particular bin above, or is it implementation dependent?</p>
</blockquote>
<p>很确定Python只是简单地委托给底层系统,所以它主要依赖于硬件。如果需要保证,请使用<code>decimal</code>。IIRC本机(C)实现在3.3中被合并,因此使用小数对性能的影响比Python2要小得多。你知道吗</p>