Sympy TypeError:使用sympy时无法确定关系的真值

问题描述:

我正在学习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

谢谢。

问题是您在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无法确定这些值的顺序,所以会出现错误。