Python字典浮游物 [英] Python Dictionary Floats

查看:157
本文介绍了Python字典浮游物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python(2.6.1)字典中遇到了一个奇怪的行为:
$ b $ p我的代码是:

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


$ b 结果是:

$ $ p $ 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的问题,每个使用二进制浮点的语言(几乎每种主流语言)都会出现这个问题。 >

    浮点指南: / b>


    由于内部计算机使用的格式(二进制浮点)
    不能准确表示数字,如0.1,0.2或0.3

    在编译或解释代码时,您的0.1已经是
    ,并以该格式四舍五入到最接近的数字,
    四舍五入错误甚至在计算发生之前。

    一些值可以完全重新生成表示为二进制小数,输出格式化例程通常显示的是最接近实际值的最短数字,而不是其他任何浮点数字,这些浮点数字掩盖了一些舍入错误。

    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

    解决方案

    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:

    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.

    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字典浮游物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆