【问题标题】:Python: Piecewise function integration error: "TypeError: cannot determine truth value of ..."Python:分段函数集成错误:“TypeError:无法确定......的真值”
【发布时间】:2016-03-13 14:24:14
【问题描述】:

这段代码运行正确:

import sympy as sp

def xon (ton, t):
    return (t-ton)/5

xonInt = sp.integrate (xon(ton, t),t)

print xonInt

但是当函数变成分段时,例如:

import sympy as sp

def xon (ton, t):
    if ton <= t:
        return (t-ton)/5
    else:
        return 0

xonInt = sp.integrate (xon(ton, t),t)

print xonInt

我收到以下错误:

文件“//anaconda/lib/python2.7/site-packages/sympy/core/relational.py”,行> 103,在非零 raise TypeError("无法确定\n%s的真值" % self)

TypeError: 无法确定真值 吨

据我了解,错误是由于tont 可以是正数和负数。这是正确的吗?如果我为t 设置正积分限制,则错误不会消失。如何计算给定分段函数的积分?

更新:功能的更新版本,有效:

import sympy as sp

t = sp.symbols('t')   
ton = sp.symbols('ton')
xon = sp.Piecewise((((t-ton)/5), t <= ton), (0, True))

xonInt = sp.integrate (xon,t)
print xonInt

【问题讨论】:

  • 什么是ton,什么是t
  • 两个符号变量。这是我的代码的简化版本。在最终代码中,t 将表示时间轴(可以取负值和正值),ton 将表示开始时间(也可以是负值和正值)。
  • 即使积分限制是数字,我也会收到错误,因此,我认为它不是重复的。
  • 仔细阅读这篇文章。 t &lt; ton 是一个符号比较,而不是布尔比较。试试print(type(t &lt; ton))bool(t &lt; ton)。设置分段函数的正确方法是在那篇文章中,在你的情况下,应该是xon = sp.Piecewise(((t-ton)/5, t &gt;= ton), (0, True))

标签: python sympy integrate piecewise


【解决方案1】:

分段类

您需要使用 sympy Piecewise class

根据 cmets 的建议:

Piecewise(((t - ton)/5, ton <= t), (0, True))

【讨论】:

  • @Tanja 对于后代,您可能会发布更新的功能。我很高兴它成功了!
  • 具体来说,Piecewise(((t - ton)/5, ton &lt;= t), (0, True))
猜你喜欢
  • 1970-01-01
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
  • 2016-10-12
  • 1970-01-01
  • 2021-08-11
相关资源
最近更新 更多