2

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")
James McGuigan
  • 7,542
  • 4
  • 26
  • 29
Kali-p
  • 23
  • 6
  • At 3 decimal points `0.32745` rounds down and `0.32788` rounds up, so they are not equal. Perhaps you were looking for floor instead of round? Take a look at this solution: https://stackoverflow.com/a/58065394/1011724 – Dan May 11 '20 at 09:48
  • You wrote you would like to compare the values in the array with 5 decimal places, but you have rounded them to 3 decimal places. – quantummind May 11 '20 at 09:48

2 Answers2

4

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.

Dan
  • 45,079
  • 17
  • 88
  • 157
1

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
James McGuigan
  • 7,542
  • 4
  • 26
  • 29