Python 字典浮点数
我在 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
I came across a strange behavior in Python (2.6.1) dictionaries:
The code I have is:
new_item = {'val': 1.4}
print new_item['val']
print new_item
And the result is:
1.4
{'val': 1.3999999999999999}
Why is this? It happens with some numbers, but not others. For example:
- 0.1 becomes 0.1000...001
- 0.4 becomes 0.4000...002
- 0.7 becomes 0.6999...996
- 1.9 becomes 1.8888...889
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是 Python 特有的,每个使用二进制浮点的语言(几乎是每个主流语言)都会出现这个问题。
来自浮点指南:
某些值可以精确地表示为二进制分数,并且输出格式化例程通常会显示比任何其他浮点数更接近实际值的最短数字,这掩盖了一些舍入错误。
This is not Python-specific, the issue appears with every language that uses binary floating point (which is pretty much every mainstream language).
From the Floating-Point Guide:
Some values can be exactly represented as binary fraction, and output formatting routines will often display the shortest number that is closer to the actual value than to any other floating-point number, which masks some of the rounding errors.
正如其他人指出的那样,这个问题与二进制浮点表示有关。
但我认为你可能想要一些可以帮助你解决 Python 中隐含问题的东西。
它与词典无关,所以如果我是你,我会删除该标签。
如果您可以根据需要使用固定精度的十进制数,我建议您查看 Python小数模块。从页面(强调我的):
This problem is related to floating point representations in binary, as others have pointed out.
But I thought you might want something that would help you solve your implied problem in Python.
It's unrelated to dictionaries, so if I were you, I would remove that tag.
If you can use a fixed-precision decimal number for your purposes, I would recommend you check out the Python decimal module. From the page (emphaisis mine):