擅长:python、mysql、java
<p>如user2357112所述,此代码来自FDLIBM。这是为IEEE-754机器精心编写的,其中C双精度有53位。它并不真正关心2的实际日志是什么,而是非常关心<code>log(2)</code>的最佳53位近似值。在</p>
<p>要重现预期的53位精确值,<a href="http://www.exploringbinary.com/number-of-digits-required-for-round-trip-conversions/" rel="noreferrer">17 decimal digits would have sufficed</a>。在</p>
<p>那么为什么他们用21位小数呢?我的猜测是:21位小数是保证转换后的结果正确到64位精度所需的最小值。如果编译器以某种方式决定将文本转换为Pentium的80位浮点格式(精度为64位),那么这在当时可能是个问题。在</p>
<p>因此,他们用足够的十进制数字显示53位结果,这样<em>如果</em>它被转换成精度为64位的二进制浮点格式,那么后面的11位(=64-53)将全部为零,从而确保他们从一开始就使用他们想要的53位值。在</p>
<pre><code>>>> import mpmath
>>> x = mpmath.log(2)
>>> x
mpf('0.69314718055994529')
>>> mpmath.mp.prec = 64
>>> y = mpmath.mpf("0.693147180559945286227")
>>> x == y
True
>>> y
mpf('0.693147180559945286227')
</code></pre>
<p>在英语中,<code>x</code>是<code>log(2)</code>的53位精确值,<code>y</code>是将代码中的十进制字符串转换为精度为64位的二进制浮点格式的结果。它们是一样的。在</p>
<p>在当前的现实中,我希望所有的编译器都能将文本转换成本地的IEEE-754双精度格式,精度为53位。在</p>
<p>无论哪种方式,代码都确保使用<code>log(2)</code>的最佳53位近似值。在</p>