Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

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

Writer Sophia Terry

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 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy