Function to determine if two numbers are nearly equal when rounded to n significant decimal digits

前端 未结 11 1896

I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be

11条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 02:57

    As of Python 3.5, the standard way to do this (using the standard library) is with the math.isclose function.

    It has the following signature:

    isclose(a, b, rel_tol=1e-9, abs_tol=0.0)
    

    An example of usage with absolute error tolerance:

    from math import isclose
    a = 1.0
    b = 1.00000001
    assert isclose(a, b, abs_tol=1e-8)
    

    If you want it with precision of n significant digits, simply replace the last line with:

    assert isclose(a, b, abs_tol=10**-n)
    

提交回复
热议问题