2016-04-26 69 views
3

我有以下代碼:如何定義分段函數沒有「類型錯誤:無法確定真值」

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) 
) 

導致到錯誤:

TypeError: cannot determine truth value of Relational 

什麼是正確的方法定義這個功能?我需要對此表示慰問,因爲我打算稍後將其整合。

回答

2

SymPy的Piecewise類does not support chained inequalities0 < x < 1。可以使用And(0 < x, x < 1)代替,但在您的示例中,這是不必要的。回想一下,從左到右評估條件;第一個評估爲真的勝。所以,你不需要在第二個狀態0 <= x,或在第三l/3 < x,等你的功能應該被定義由

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

謝謝!這有幫助。 – UpmostScarab

+0

SymPy通常不支持鏈式不等式,因爲它們[不可能支持](http://docs.sympy.org/latest/modules/core.html#r72)。你可以使用'And(0 asmeurer

相關問題