0

If I run the following code it does not recognize several of the numbers in the array, like 0.1, even though it looks like 0.1 is in the array when it is printed.

import numpy as np

pH = 0.1

print(np.linspace(0.0, 2.9, num=30))

if pH in np.linspace(0.0, 2.9, num=30):
    print("it doesn't recognize 0.1")

pH = 0.3

if pH in np.linspace(0.0, 2.9, num=30):
    print('however it does recognize 0.3')

Output:

[0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.  2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9]
however, it does recognize 0.3
Das_Geek
  • 2,775
  • 7
  • 20
  • 26

2 Answers2

1

This fault is mainly due to the fact that NumPy and Python are somewhat finicky when it comes to storing, and consequently, comparing floating point integers.

We can see that python's 0.1 is actually:

>>> print('{0:.20f}'.format(0.1))
0.10000000000000000555

while NumPy's 0.1 is actually:

>>> import numpy as np
>>> print('{0:.20f}'.format(np.linspace(0.0, 2.9, num=30)[1])) # 0.1 in list
0.09999999999999999167

Therefore, to properly compare these, you can use the provided math.isclose() or numpy.isclose() (compares two lists):

import math

# -- snip --

for num in np.linspace(0.0, 2.9, num=30):
    if math.isclose(0.1, num):
        print('detected!')
Sergey Ronin
  • 756
  • 7
  • 23
0

It seems like the value the numpy array is displaying is different than the actual value. Probably due to floating point accuracy. If you want a way to get around this you could use a list comprehension.

import numpy as np

pH = 0.1

print(np.linspace(0.0, 2.9, num=30))

if pH in [round(x, 5) for x in np.linspace(0.0, 2.9, num=30)]:
    print("it does recognize 0.1")
Axe319
  • 4,255
  • 3
  • 15
  • 31