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

亡梦爱人 提交于 2020-08-26 06:46:41

问题


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].


回答1:


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



来源:https://stackoverflow.com/questions/29307980/how-to-make-my-piecewise-function-zero-outside-the-provided-interval-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!