np.piecewise generates incorrect values for integer array

Question:

I have a numpy piecewise function defined as

def function(x):
    return np.piecewise(x, [x <= 1, x > 1], [lambda x: 1/2*np.sin((x-1)**2), lambda x:-1/2*np.sin((x-1)**2)])

I have no idea why this function is returning incorrect values for various x-values. In particular, running the following

X = np.array([0,2.1])
Y = np.array([0,2])
A = function(X)
B = function(Y)

will give A = array([ 0.42073549, -0.467808 ]), but B = array([0, 0]). Why is this happening?

I am expecting B = array([0.42073549, -0.468ish]).

Asked By: harkins 2011

||

Answers:

Look at the types of your data.

X is an array of floats. But Y is an array of int.

And, quoting documentation of piecewise

The output is the same shape and type as x

So, output of piecewise when called with Y, that is an array of shape (2,) and dtype int64, is forced to be an array of shape (2,) and dtype int64. And the closest int64 to 0.42073549, -0.468ish are 0 and 0.

Just replace Y by np.array([0,2.0]) (to force float type), or np.array([0, 2], dtype=np.float64),

Answered By: chrslg
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.