Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

piecewise numpy function with integer arguments

I define the piecewise function

def Li(x):        
    return piecewise(x, [x < 0, x >= 0], [lambda t: sin(t), lambda t: cos(t)])

And when I evaluate Li(1.0)

The answer is correct

Li(1.0)=array(0.5403023058681398),

But if I write Li(1) the answer is array(0).

I don't understand this behaviour.

like image 362
yomismo Avatar asked May 07 '26 07:05

yomismo


2 Answers

This function runs correctly.

def Li(x):        
  return  piecewise(float(x), 
                    [x < 0, x >= 0], 
                    [lambda t: sin(t), lambda t: cos(t)])
like image 197
yomismo Avatar answered May 09 '26 12:05

yomismo


It seems that piecewise() converts the return values to the same type as the input so, when an integer is input an integer conversion is performed on the result, which is then returned. Because sine and cosine always return values between −1 and 1 all integer conversions will result in 0, 1 or -1 only - with the vast majority being 0.

>>> x=np.array([0.9])
>>> np.piecewise(x, [True], [float(x)])
array([ 0.9])
>>> x=np.array([1.0])
>>> np.piecewise(x, [True], [float(x)])
array([ 1.])
>>> x=np.array([1])
>>> np.piecewise(x, [True], [float(x)])
array([1])
>>> x=np.array([-1])
>>> np.piecewise(x, [True], [float(x)])
array([-1])

In the above I have explicitly cast the result to float, however, an integer input results in an integer output regardless of the explicit cast. I'd say that this is unexpected and I don't know why piecewise() should do this.

I don't know if you have something more elaborate in mind, however, you don't need piecewise() for this simple case; an if/else will suffice instead:

from math import sin, cos

def Li(t):        
    return sin(t) if t < 0 else cos(t)

>>> Li(0)
1.0
>>> Li(1)
0.5403023058681398
>>> Li(1.0)
0.5403023058681398
>>> Li(-1.0)
-0.8414709848078965
>>> Li(-1)
-0.8414709848078965

You can wrap the return value in an numpy.array if required.

like image 39
mhawke Avatar answered May 09 '26 12:05

mhawke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!