Sympy TypeError:使用 sympy 时无法确定 Relational 的真值 [英] Sympy TypeError: cannot determine truth value of Relational when using sympy

查看:315
本文介绍了Sympy TypeError:使用 sympy 时无法确定 Relational 的真值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 SymPy.这是我遇到的问题:

x = symbols('x',real=True)h = 符号('h',real=True)f = 符号('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')模式 = [arg.match(c*f(w)) for arg in expr_diff.args]系数 = [t[c] for t in sorted(patterns, key=lambda t:t[w])]打印(系数)

但是我遇到了以下错误:

<块引用>

TypeError Traceback(最近一次调用最后) 在 ()----> 1 系数 = [t[c] for t in sorted(patterns, key=lambda t:t[w])]2 打印(系数)

C:\Program Files\Anaconda3\lib\site-packages\sympy\core\relational.py在非零(自我)193194 def 非零(自我):--> 195 raise TypeError("无法确定关系的真值")196197 bool = 非零

TypeError:无法确定 Relational 的真值

我使用的是 Windows 7Python 3.5.2Anaconda 3.

谢谢.

解决方案

问题在于您对 patterns 执行的排序.

sorted(patterns, key=lambda t:t[w]) 尝试返回按 wpatterns>,但这些值无法相互比较.

这是为什么?因为它们是关系"值,意味着它们取决于其中变量的值.让我们检查一下:

<预><代码>>>>[t[w] 表示模式中的 t][-h + x, -3*h + x, -2*h + x, x]

-h + x 大于 -3*h + x 还是相反?好吧,这取决于 hx 是什么,并且由于 SymPy 无法确定这些值的顺序,因此会出现错误.

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.

解决方案

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.

这篇关于Sympy TypeError:使用 sympy 时无法确定 Relational 的真值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆