0

I am using np.isclose() to compare 2 float values but for some usecases this doesn't work as expected.

For example

np.isclose([1000.01], [1000.02])

returns True but it should return False.

I cannot make rtol to 0.0 as I need to compare these values upto 3 decimal places only.

Aditya Sahu
  • 65
  • 1
  • 8
  • [There is no general solution for comparing floating-point numbers that contain errors from previous operations.](https://stackoverflow.com/a/56040270/298225). Any comparison is application-specific, so you need to provide more context, such as explaining what you are doing and what errors the numbers could contain (bounds on them). – Eric Postpischil Apr 05 '21 at 16:18

1 Answers1

4

np.isclose(a, b, rtol=10**-5, atol=10**-8) checks:

np.abs(a - b) <= (atol + rtol * np.abs(b))

This means that for your values ~1000 and the defaults it will return True if the differences are

<= (10**-8 + 10**-5 * np.abs(1000))
<= 0.01000001

So your values are within that distance, thus it evaluates to True.


If your requirement is

I need to compare these values up to 3 decimal places only.

Then you don't want a relative tolerance, and instead you want only to specify an absolute tolerance.

np.isclose([1000.01, 1000.0013, 1000.0047, 1000.0041, 1000.0045], 
           [1000.02, 1000.0014, 1000.0052, 1000.0052, 1000.005500001],
           rtol=0, atol=10**-3)

#array([False,  True,  True, False, False])
ALollz
  • 57,915
  • 7
  • 66
  • 89