numpy round compare array

Viewed 922

I'm currently working with the numpy float array.

My problem is that I'd like to compare them with, say, 3 decimal places.

But when I try to use round or around, it doesn't work.

If you know a way I'd be very grateful.

Here's the code I tried

import numpy as np

x = np.array(([0.32745, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)
y = np.array(([0.32788, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)

x = np.round(x, 3)
y = np.round(y, 3)

if (x == y).all():
    print("ok")
2 Answers

At 3 decimal points 0.32745 rounds down and 0.32788 rounds up, so they are not equal. An easier solution might be to use numpy's isclose setting the absolute precision argument atol:

import numpy as np

decimal_points = 3

x = np.array(([0.32745, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)
y = np.array(([0.32788, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)

if np.isclose(x, y, atol=1e-decimal_points).all():
    print("ok")  

There is also allclose which would allow you to drop your call to .all()

This will compare if the absolute difference between the numbers is lower than your precision requirement, so in this case lower than 0.001. This is subtly different from rounding (or flooring), but since you expected the data in your question to match, I think this is actually what you meant.

Your basic idea is correct, but your data is wrong.

The first numbers in x and y round to 0.327 and 0.328, which is why your equality statement (correctly) returns false. Try rounding them to 2 decimal places, and everything works as expected.

>>> np.round(x,3)
array([[ 0.327, -1.043, -0.633],
       [ 0.418, -1.038, -1.166]])
>>> np.round(y,3)
array([[ 0.328, -1.043, -0.633],
       [ 0.418, -1.038, -1.166]])
>>> np.round(x,2) == np.round(y,2)
array([[ True,  True,  True],
       [ True,  True,  True]])
>>> (np.round(x,2) == np.round(y,2)).all()
True
Related