Reputation: 29099
In numpy you can use the allclose(X, Y)
function to check element-wise for approximate equality between two arrays. Moreover, with an expression like X==5
you can check element-wise equality between an array and a scalar.
Is there a function that combines both functionalities?? That is, can compare an array and a scalar for approximate element-wise equality??
Upvotes: 3
Views: 2120
Reputation: 152725
The term array or array-like in the numpy documentation mostly indicates that the input is converted to an array with np.asarray(in_arg)
or np.asanyarray(in_arg)
. So if you input a scalar it will be converted to an scalar array:
>>> import numpy as np
>>> np.asarray(5) # or np.asanyarray
array(5)
And the functions np.allclose
or np.isclose
just do element-wise comparison no matter if the second argument is a scalar array, an array with the same shape or an array that correctly broadcasts to the first array:
>>> import numpy as np
>>> arr = np.array([1,2,1,0,1.00001,0.9999999])
>>> np.allclose(arr, 1)
False
>>> np.isclose(arr, 1)
array([ True, False, True, False, True, True], dtype=bool)
>>> np.isclose(arr, np.ones((10, 6)))
array([[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True],
[ True, False, True, False, True, True]], dtype=bool)
So no need to find another function that explicitly handles scalars, these functions already correctly work with scalars.
Upvotes: 2