打印超出其精度的浮点数

Printing a Float Beyond Its Precision

当我运行这段代码时,

print('{:.15f}'.format(123456789.55555555555555555555555555555555555555))
print('{:.25f}'.format(0.5555555555555555555555555555555555555555555555))

我得到这个输出:

123456789.555555552244186
0.5555555555555555802271783

这些额外的数字是从哪里来的(123456789.555555552244186,0.5555555555555555802271783),为什么它们不是零?

我猜它们是由转换算法生成的,没有意义,但我想了解更多这方面的信息。如果转换算法使它们为零就好了。

当您尝试存储这些值时,实际存储的是最接近的可表示双精度二进制浮点值。这就是正在打印的内容。所以这些额外的数字实际上是有意义的——它们代表存储的实际值。

Rob Kennedy's useful web page which shows the closest representable floating point number to a given value. As you can see, the closest double precision value to your first value是:

+ 1234 56789.55555 55522 44186 40136 71875

closest double precision value to your second value 是:

+ 0.55555 55555 55555 58022 71783 25003 47867 60807 03735 35156 25

这些值与 Python 产生的相匹配。

所以,这纯粹是一个代表性问题。更多关于浮点数的参考资料: