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

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

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)

There is a function assert_approx_equal in numpy.testing (source here) which may be a good starting point.

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 – Function to determine if two numbers are nearly equal when rounded to n significant decimal digits

Heres a take.

def nearly_equal(a,b,sig_fig=5):
    return ( a==b or 
             int(a*10**sig_fig) == int(b*10**sig_fig)
           )

Leave a Reply

Your email address will not be published. Required fields are marked *