如何在没有“TypeError:无法确定真值”的情况下定义分段函数

时间:2022-09-26 16:54:07

I have the following code:

我有以下代码:

l = 2
h = 1
p = 2
q = -2
x = Symbol('x')
f = Piecewise ( (0, x < 0),
               (p, 0 <= x <= l/3),
               (h/l * x - h, l/3 < x  < 2*l/3),
               (q, 2*l/3 <= x  <= l),
               (0, x > l)
)

which results into a Error:

这会导致错误:

TypeError: cannot determine truth value of Relational

What is the proper way to define this function? I need sympy for this because I plan to integrate it later.

定义此功能的正确方法是什么?我需要同情,因为我打算稍后整合它。

1 个解决方案

#1


2  

SymPy's Piecewise class does not support chained inequalities like 0 < x < 1. It is possible to use And(0 < x, x < 1) instead, but in your example this is unnecessary. Recall that the conditions are evaluated from left to right; the first that evaluates to True wins. So you don't need 0 <= x in the second condition, or l/3 < x in the third, etc. Your function should be defined by

SymPy的Piecewise类不支持像0

f = Piecewise ( (0, x < 0),
                (p, x <= l/3),
                (h/l * x - h, x < 2*l/3),
                (q, x <= l),
                (0, True)
)

#1


2  

SymPy's Piecewise class does not support chained inequalities like 0 < x < 1. It is possible to use And(0 < x, x < 1) instead, but in your example this is unnecessary. Recall that the conditions are evaluated from left to right; the first that evaluates to True wins. So you don't need 0 <= x in the second condition, or l/3 < x in the third, etc. Your function should be defined by

SymPy的Piecewise类不支持像0

f = Piecewise ( (0, x < 0),
                (p, x <= l/3),
                (h/l * x - h, x < 2*l/3),
                (q, x <= l),
                (0, True)
)