Search code examples
pythonnumpypiecewise

Python, numpy, piecewise answer gets rounded


I have a question with regards to the outputs of numpy.piecewise.

my code:

e=110
f=np.piecewise(e,[e<120,e>=120],[1/4,1])
print(f)

As a result i get: 0 and not the desired 0.25

Can someone explain me why piecewise seems to be rounding my answer? Is there a way to go around this without doing?

e=110
f=np.piecewise(e,[e<120,e>=120],[1,4])/4
print(f)

many thanks in advance


Solution

  • From the np.piecewise docs:

    The output is the same shape and type as x

    Integer in, integer out. If you want a floating-point output, you need to pass a float in:

    e = 110.0
    

    Additionally, if you're on Python 2, 1/4 will already just be 0 because that's floor division on Python 2, so you'll need to write something like 1.0/4.0 or just 0.25.