Skip to content
Advertisement

comparing numpy arrays with tolerance

I’m trying to compare floating numbers that are stored in numpy arrays. I would like them to be compared with a tolerance and every number of the array should be compared with every number of the other array. My attempt is shown underneath, I used two simple arrays as examples but it has the problem that it only compares numbers with the same indices.

b_y_ion_mass =  np.array([1.000, 2.1300, 3.4320, 6.0000]) 
observed_mass_array = np.array([0.7310, 2.2300, 5.999, 8.000, 9.000])

abs_tol = 0.2 

for (fragment, mass) in zip(b_y_ion_mass, observed_mass_array): 
    if (fragment+abs_tol)> mass and (fragment-abs_tol)< mass:
        print(mass)

It would be great if anyone could help me.

Thank you.

Advertisement

Answer

Use np.isclose with atol = abs_tol.

import numpy as np

b_y_ion_mass =  np.array([1.000, 2.1300, 3.4320, 6.0000]) 
observed_mass_array = np.array([0.7310, 2.2300, 5.999, 8.000, 9.000])
 
abs_tol = 0.2

np.isclose( b_y_ion_mass, observed_mass_array[ :, None ] , atol = abs_tol )
#           columns       rows

# array([[False, False, False, False],
#        [False,  True, False, False],
#        [False, False, False,  True],
#        [False, False, False, False],
#        [False, False, False, False]])

# Compares
#          [1.000, 2.1300, 3.4320, 6.0000]
# [0.7310, 
#  2.2300,         True
#   5.999,                         True 
#   8.000, 
#   9.000]

To get the observed masses:

np.isclose( b_y_ion_mass, observed_mass_array[ :, None ], 
            atol = abs_tol ) * observed_mass_array[ :, None ]

Result

array([[0.   , 0.   , 0.   , 0.   ],
       [0.   , 2.23 , 0.   , 0.   ],
       [0.   , 0.   , 0.   , 5.999],
       [0.   , 0.   , 0.   , 0.   ],
       [0.   , 0.   , 0.   , 0.   ]])
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement