Skip to main content
 首页 » 编程设计

Python 字典 float

2025年05月04日9虾米姐

我在 Python (2.6.1) 字典中遇到了一个奇怪的行为:

我的代码是:

new_item = {'val': 1.4} 
print new_item['val'] 
print new_item 

结果是:

1.4 
{'val': 1.3999999999999999} 

这是为什么?它发生在某些数字上,但不会发生在其他数字上。例如:

  • 0.1 变为 0.1000...001
  • 0.4 变为 0.4000...002
  • 0.7 变为 0.6999...996
  • 1.9 变为 1.8888...889

请您参考如下方法:

这不是 Python 特有的,每个使用二进制 float 的语言(几乎所有主流语言)都会出现这个问题。

来自Floating-Point Guide :

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

有些值可以精确地表示为二进制小数,并且输出格式化例程通常会显示最短的数字,该数字比任何其他 float 更接近实际值,这掩盖了一些舍入误差。