Skip to main content
 首页 » 编程设计

python之理解 float 文档

2025年05月04日15thcjp

我正在阅读有关 floating-point issues and limits 的 Python 文档.

在页面的一半左右,它说:

Interestingly, there are many different decimal numbers that share the same nearest approximate binary fraction. For example, the numbers 0.1 and 0.10000000000000001 and 0.1000000000000000055511151231257827021181583404541015625 are all approximated by 3602879701896397 / 2 ** 55. Since all of these decimal values share the same approximation, any one of them could be displayed while still preserving the invariant eval(repr(x)) == x.

特别是,它想表达什么:

Since all of these decimal values share the same approximation, any one of them could be displayed while still preserving the invariant eval(repr(x)) == x

Python 不会截断超过 15 位小数的 float 吗?有例子吗?

请您参考如下方法:

重点是无论最初提供了多少额外的数字,repr() 都会得到相同的输出,

>>> repr(0.1) 
'0.1' 
>>> repr(0.1000000000000000055511151231257827021181583404541015625) 
'0.1' 

那么,为什么它不为两者打印更长的版本呢?

# Hypothetically... 
>>> repr(0.1) 
'0.1000000000000000055511151231257827021181583404541015625' 
>>> repr(0.1000000000000000055511151231257827021181583404541015625) 
'0.1000000000000000055511151231257827021181583404541015625' 

因此,有多种方法可以打印出相同的数字。 Python 使用 dtoa() 函数选择最短方式打印给定数字,在本例中,最短方式为0.1 .

0.1 实际上并不准确:准确的结果是较长的结果,但 dtoa() 在打印时将数字四舍五入,只要四舍五入读回时,数字将四舍五入为原始数字。换句话说,

float(repr(x)) == x 

...即使 float() 和 repr() 都舍入了它们的参数。