2017-10-19 658 views
1

我正在學習SymPy。這裏是我的問題:Sympy TypeError:使用sympy時無法確定關係的真值

x = symbols('x',real=True) 
h = symbols('h',real=True) 
f = symbols('f',cls=Function)  
sym_dexpr = f_diff.subs(f(x), x*exp(-x**2)).doit() 
f_diff = f(x).diff(x,1) 
expr_diff = as_finite_diff(f_diff, [x, x-h,x-2*h,x-3*h]) 
w=Wild('w') 
c=Wild('c') 
patterns = [arg.match(c*f(w)) for arg in expr_diff.args] 
coefficients = [t[c] for t in sorted(patterns, key=lambda t:t[w])] 
print(coefficients) 

但我得到以下錯誤

TypeError Traceback (most recent call last) in() ----> 1 coefficients = [t[c] for t in sorted(patterns, key=lambda t:t[w])] 2 print(coefficients)

C:\Program Files\Anaconda3\lib\site-packages\sympy\core\relational.py in nonzero(self) 193 194 def nonzero(self): --> 195 raise TypeError("cannot determine truth value of Relational") 196 197 bool = nonzero

TypeError: cannot determine truth value of Relational

我使用Windows 7Python 3.5.2Anaconda 3

謝謝。

回答

0

問題是您在patterns上執行的排序。

sorted(patterns, key=lambda t:t[w])嘗試返回patterns按密鑰w的每個項目的值排序,但這些值不能相互比較。

這是爲什麼?因爲它們是「關係」值,意味着它們依賴於變量的值。讓我們檢查:

>>> [t[w] for t in patterns] 
[-h + x, -3*h + x, -2*h + x, x] 

-3*h + x或周圍的其他方式更大-h + x?那麼這取決於hx是什麼,並且由於SymPy無法確定這些值的順序,所以會出現錯誤。