我被要求测试第三方提供的库。已知该库精确到 n 个有效数字。任何不太重要的错误都可以安全地忽略。我想写一个函数来帮助我比较结果:

def nearlyequal( a, b, sigfig=5 ):

此函数的目的是确定两个浮点数(a 和 b)是否近似相等。如果 a==b(完全匹配)或者 a 和 b 在四舍五入为 sigfig 有效数字时具有相同的值,则该函数将返回 True。

有人可以建议一个好的实现吗?我写了一个迷你单元测试。除非你能在我的测试中看到一个错误,否则一个好的实现应该通过以下几点:
assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal( 1e4, 1e4 + 1, 5)
assert nearlyequal( 0.0, 1e-15, 5 )
assert not nearlyequal( 0.0, 1e-4, 6 )

补充笔记:
  • 值 a 和 b 可能是 int、float 或 numpy.float64 类型。值 a 和 b 将始终属于同一类型。转换不会在函数中引入额外的错误,这一点至关重要。
  • 让我们保持这个数值,因此转换为字符串或使用非数学技巧的函数并不理想。该程序将由一位数学家进行审核,他希望能够证明该函数完成了它应该做的事情。
  • 速度...我必须比较很多数字,所以越快越好。
  • 我有 numpy、scipy 和标准库。其他任何东西对我来说都很难得到,尤其是对于项目的这么一小部分。
  • 最佳答案

    assert_approx_equal 中有一个函数 numpy.testing(来源 here) ,这可能是一个很好的起点。

    def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=True):
        """
        Raise an assertion if two items are not equal up to significant digits.
    
        .. note:: It is recommended to use one of `assert_allclose`,
                  `assert_array_almost_equal_nulp` or `assert_array_max_ulp`
                  instead of this function for more consistent floating point
                  comparisons.
    
        Given two numbers, check that they are approximately equal.
        Approximately equal is defined as the number of significant digits
        that agree.
    

    关于python - 当四舍五入为 n 个有效十进制数字时,用于确定两个数字是否几乎相等的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/558216/

    10-14 19:01
    查看更多