Sohail
Sohail

Reputation: 319

How to make my Piecewise function zero outside the provided interval in python

Here is my code:

    In [61]: import sympy as sp

    In [62]: x = sp.Symbol('x')

    In [63]: phi_1 = sp.Piecewise( ( (1.3-x)/0.3, 1<=x <=1.3 ))

    In [64]: phi_1.subs(x,1.2)
    Out[64]: 0.333333333333334

    In [65]: phi_1.subs(x,1.4)
    Out[65]: Piecewise()

More specifically, I want to get zero as an answer to the input no. 65, since 1.4 is outside the interval [1, 1.3].

Upvotes: 1

Views: 10005

Answers (1)

jedwards
jedwards

Reputation: 30210

You need to tell Piecewise that you want the function to evaluate to zero when outside the bounds, for example:

import sympy as sp

x = sp.Symbol('x')

phi_1 = sp.Piecewise(
    (0, x < 1),
    (0, x > 1.3),
    ( (1.3-x)/0.3, True )
)

print(phi_1.subs(x,1.2)) # 0.333333333333334

print(phi_1.subs(x,1.4)) # 0

Note that this syntax works in 0.7.1 and 0.7.6 -- your code raises an TypeError in 0.7.6 with the "compound conditional" 1 <=x <=1.3

Upvotes: 9

Related Questions