Sympy TypeError: cannot determine truth value of Relational when using sympy

可紊 提交于 2020-01-05 04:13:14

问题


I'm learning SymPy now. Here is the problem I got:

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)

But I got following error:

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

I am using Windows 7, Python 3.5.2 and Anaconda 3.

Thank you.


回答1:


The problem is the sort you perform on patterns.

sorted(patterns, key=lambda t:t[w]) attempts to return patterns sorted by every item's value for the key w, yet these values can not be compared with each other.

Why is that? because they are "relational" values, means they depend on the values of the variable in them. Lets check:

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

Is -h + x greater than -3*h + x or the other way around? well, that depends on what h and x are, and since SymPy can't determine the order of these values, you get an error.



来源:https://stackoverflow.com/questions/46823004/sympy-typeerror-cannot-determine-truth-value-of-relational-when-using-sympy

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