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.
JavaScript
x
9
1
b_y_ion_mass = np.array([1.000, 2.1300, 3.4320, 6.0000])
2
observed_mass_array = np.array([0.7310, 2.2300, 5.999, 8.000, 9.000])
3
4
abs_tol = 0.2
5
6
for (fragment, mass) in zip(b_y_ion_mass, observed_mass_array):
7
if (fragment+abs_tol)> mass and (fragment-abs_tol)< mass:
8
print(mass)
9
It would be great if anyone could help me.
Thank you.
Advertisement
Answer
Use np.isclose
with atol = abs_tol.
JavaScript
1
24
24
1
import numpy as np
2
3
b_y_ion_mass = np.array([1.000, 2.1300, 3.4320, 6.0000])
4
observed_mass_array = np.array([0.7310, 2.2300, 5.999, 8.000, 9.000])
5
6
abs_tol = 0.2
7
8
np.isclose( b_y_ion_mass, observed_mass_array[ :, None ] , atol = abs_tol )
9
# columns rows
10
11
# array([[False, False, False, False],
12
# [False, True, False, False],
13
# [False, False, False, True],
14
# [False, False, False, False],
15
# [False, False, False, False]])
16
17
# Compares
18
# [1.000, 2.1300, 3.4320, 6.0000]
19
# [0.7310,
20
# 2.2300, True
21
# 5.999, True
22
# 8.000,
23
# 9.000]
24
To get the observed masses:
JavaScript
1
3
1
np.isclose( b_y_ion_mass, observed_mass_array[ :, None ],
2
atol = abs_tol ) * observed_mass_array[ :, None ]
3
Result
JavaScript
1
6
1
array([[0. , 0. , 0. , 0. ],
2
[0. , 2.23 , 0. , 0. ],
3
[0. , 0. , 0. , 5.999],
4
[0. , 0. , 0. , 0. ],
5
[0. , 0. , 0. , 0. ]])
6