I am getting weird results from numpy sqrt method when applying it on an array of integers with a where condition. See below.
With integers:
a = np.array([1, 4, 9])
np.sqrt(a, where=(a>5))
Out[3]: array([0. , 0.5, 3. ])
With floats:
a = np.array([1., 4., 9.])
np.sqrt(a, where=(a>5))
Out[25]: array([1., 4., 3.])
Is it a bug or a misunderstanding of how this method works?
I think there might be a
buginconsistency*, when repeating the command several times I don't get consistent results.*this is actually due to the probable use of
numpy.emptyto initialize the output. This function reuses memory without setting the default values and thus will have non-predictable values in the cells that are not manually overwritten.Here is an example:
Output:
From the remark of @hpaulj, it seems that providing
outis required. Indeed, this prevents the inconsistent behavior with the above example.outshould be initialized with a predictable function, such asnumpy.zeros.Output:
Nevertheless, this seems to be an inconsistent behavior.
The doc specifies that it out is not provided, a new array should be allocated:
In your case you rather want to use
numpy.where:Output:
array([1., 4., 3.])