【问题标题】:Adding decimal numbers to a decimal number not working properly in python [duplicate]将十进制数添加到十进制数在python中无法正常工作[重复]
【发布时间】:2013-06-12 04:01:30
【问题描述】:

我正在尝试将十进制数添加为十进制数,它可以正常工作,但是当我执行1.1 + 0.1 时,我得到1.2000000000000002,但我希望它等于1.2。当我执行1.0 + 0.1 时,我得到1.1,这是完美的,但对于1.1 + 0.1,我没有得到。那么有没有办法让我摆脱1.2000000000000002中的000000000000002

谢谢。

【问题讨论】:

标签: python numbers decimal


【解决方案1】:

这是对您问题的字面答案:

float(str(1.1 + 0.1)[0:3])

如果您对问题的“原因”感兴趣,请参阅问题 cmets 中提供的链接。

【讨论】:

    【解决方案2】:

    您可以尝试字符串格式化,documentation here

    >>> "%0.2f" % float(1.1 + 0.1)
    '1.20'
    

    甚至:

    >>> "%0.1f" % float(1.1 + 0.1)
    '1.2'
    

    至于为什么,在PEP 327 here 上有明确描述。

    【讨论】:

      【解决方案3】:

      正如无数次声明的那样,0.1 不能用 IEEE 754 浮点数精确表示。您可以在What Every Computer Scientist Should Know About Floating-Point ArithmeticThe Floating Point Guide 中阅读有关原因的所有信息

      您可以对值进行截断或舍入:

      >>> round(1.1+.1,2)
      1.2
      >>> "%.*f" % (1, 1.1+.1 )
      '1.2'
      >>> s=str(1.1+.1)
      >>> s[0:s.find('.')+2]
      '1.2'
      

      如果您想要精确 表示这些值,请考虑使用Decimal module

      >>> import decimal
      >>> decimal.Decimal('1.1')+decimal.Decimal('.1')
      Decimal('1.2')
      

      请注意,您需要从浮点数的字符串表示开始,'0.1' 因为0.1 在 IEEE 浮点数中不能完全以二进制表示:

      >>> decimal.Decimal(.1)
      Decimal('0.1000000000000000055511151231257827021181583404541015625')
      

      要在计算后返回字符串表示,可以使用str

      >>> str(sum(map(decimal.Decimal,['.1','.1','.5','.5'])))
      '1.2'
      

      另一种选择是使用有理数库,例如Fractions

      >>> from fractions import Fraction as Fr
      >>> Fr(11,10)+Fr(1,10)
      Fraction(6, 5)
      

      有了这个结果,您仍然需要舍入、截断或使用任意精度的算术包来获得准确的数字(取决于输入...)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-04
        • 2018-04-03
        • 2021-08-31
        • 1970-01-01
        • 2015-06-20
        • 2013-02-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多