What is the expected effect of where in numpy's negative?

Viewed 184

As far as I understand the documentation of numpy's negative function, its where option allows you to leave some array components unnegated:

>>> import numpy as np
>>> np.negative(np.array([[1.,2.],[3.,4.],[5.,6.]]), where=[True, False])
array([[-1., 2.],
       [-3., 4.],
       [-5., 6.]])

However, when I try it, it seems that those values are (almost) zeroed instead:

>>> import numpy as np
>>> np.negative(np.array([[1.,2.],[3.,4.],[5.,6.]]), where=[True, False])
array([[-1.00000000e+000,  6.92885436e-310],
       [-3.00000000e+000,  6.92885377e-310],
       [-5.00000000e+000,  6.92885375e-310]])

So how should I see the where option?

1 Answers

The documentation describes where like this:

Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.

Let's try an example using the out parameter:

x = np.ones(3)
np.negative(np.array([4.,5.,6.]), where=np.array([False,True,False]), out=x)

This sets x to [1., -5., 1.], and returns the same.

This makes some amount of sense once you realize that "leave the value in the output alone" literally means the output value is "don't care", rather than "same as the input" (the latter interpretation was how I read it the first time, too).

The problem comes in when you specify where but not out. Apparently the "ufunc machinery" (which is not visible in the implementation of np.negative()) creates an empty output array, meaning the values are indeterminate. So the locations at which where is False will have uninitialized values, which could be anything.

This seems pretty wrong to me, but there was a NumPy issue filed about it last year, and closed. It seems unlikely to change, so you'll have to work around it (e.g. by creating the output array yourself using zeros).

Related