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

家住魔仙堡 提交于 2021-01-29 13:39:25

问题


In my researches, I couldn't find any examples related to a relational value in piecewise functions. Although I received the lower and upper values with the uni_dis method, i'm stuck in the process of transferring these values to the piecewise function. What's the reason?

from sympy import Symbol, Piecewise
import sympy as sym
import sympy.plotting as syp
import math

a = Symbol('a')
b = Symbol('b')
x = Symbol('x')
function = 1 / abs(a-b)

def uni_dis(lower, upper):
    if lower > upper:
        lower, upper = upper, lower
    uniform = Piecewise((0, x < lower), (0, x > upper), (function.subs({a:lower, b:upper}), x >= lower and x <= upper))
    syp.plot(uniform.subs((x,-10,10), title="uni_dis"))

uni_dis(231, 675)

My error message is as follows:

TypeError                                 Traceback (most recent call last)
<ipython-input-3-c28135b22fc4> in <module>
----> 1 uni_dis(231, 675)

<ipython-input-2-e4a205990c2a> in uni_dis(lower, upper)
      2     if lower > upper:
      3         lower, upper = upper, lower
----> 4     uniform = Piecewise((0, x < lower), (0, x > upper), (function.subs({a:lower, b:upper}), x >= lower and x <= upper))
      5     syp.plot(uniform.subs((x,-10,10), title="uni_dis"))

C:\ProgramData\Anaconda3\lib\site-packages\sympy\core\relational.py in __nonzero__(self)
    374 
    375     def __nonzero__(self):
--> 376         raise TypeError("cannot determine truth value of Relational")
    377 
    378     __bool__ = __nonzero__

TypeError: cannot determine truth value of Relational

回答1:


You should modify x >= lower and x <= upper to (x >= lower) & (x <= upper). The problem is that logical evaluations with SymPy objects can return an another symbolic logic that cannot be deduced to True or False. You can see how (x >= lower).__class__ returns an another sympy inequality instance.




回答2:


After correcting logical expressions, I got an " TypeError: 'Symbol' object is not subscriptable " error. After doing some research, I learned that the plot method can be used with the piecewise method as here. And that's it.

Corrected version of the code:

def uniform_dist(lower, upper):
    if lower > upper:
        lower, upper = upper, lower
    syp.plot(Piecewise((0, x < lower), (0, x > upper), (f.subs({a:lower, b:upper}), (x >= lower) & (x <= upper))), (x,-10,10), title="uniform distribution")


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

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