【问题标题】:How to calculate a value to a certain number of decimal places?如何计算某个小数位数的值?
【发布时间】:2011-01-20 08:50:01
【问题描述】:

使用 numpy 或 python 的标准库,或者。如何获取具有多个小数位的值并将其截断为 4 个小数位?我只想将浮点数与其前 4 个小数点进行比较。

【问题讨论】:

    标签: python floating-accuracy


    【解决方案1】:

    你可以使用decimal模块,尤其是getcontext().prec上的部分

    【讨论】:

      【解决方案2】:

      如果您想比较两个浮点数,可以在 abs(a-b) < epsilon 上进行比较,其中 epsilon 是您的精度要求。

      【讨论】:

        【解决方案3】:

        round(a_float, 4)

        >>> help(round)
        Help on built-in function round in module __builtin__:
        
        round(...)
            round(number[, ndigits]) -> floating point number
        
            Round a number to a given precision in decimal digits (default 0 digits).
            This always returns a floating point number.  Precision may be negative.
        
        >>>
        

        【讨论】:

          【解决方案4】:
          >>> round(1.2345678,4) == round(1.2345999,4)
          True
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-03-18
            • 1970-01-01
            • 2015-07-29
            • 2013-01-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多