TypeError:分段使用 sympy 时无法确定 Relational 的真值

在我的研究中,我找不到任何与分段函数中的关系值相关的示例。尽管我使用uni_dis方法收到了下限值和上限值,但我仍停留在将这些值传输到分段函数的过程中。什么原因?


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)

我的错误信息如下:


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


慕哥9229398
浏览 1737回答 2
2回答

繁花不似锦

您应该修改x >= lower and x <= upper为(x >= lower) & (x <= upper).&nbsp;问题在于 SymPy 对象的逻辑评估可能会返回另一个符号逻辑,该逻辑不能被推断为 True 或 False。您可以看到如何(x >= lower).__class__返回另一个 sympy 不等式实例。

胡子哥哥

更正逻辑表达式后,出现“ TypeError: 'Symbol' object is not subscriptable ”错误。经过一些研究,我了解到绘图方法可以与分段方法一起使用,如下所示。就是这样。代码的更正版本:def uniform_dist(lower, upper):&nbsp; &nbsp; if lower > upper:&nbsp; &nbsp; &nbsp; &nbsp; lower, upper = upper, lower&nbsp; &nbsp; 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")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python