我被要求测试第三方提供的库。已知该库精确到 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 )
补充笔记:
最佳答案
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/