Python:分段函数集成错误:“TypeError:无法确定......的真值”

时间:2022-09-26 16:54:19

This code runs correctly:

此代码正确运行:

import sympy as sp

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

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

print xonInt

But when the function becomes piecewise, e.g.:

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

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

I get the following error:

我收到以下错误:

File "//anaconda/lib/python2.7/site-packages/sympy/core/relational.py", line > 103, in nonzero raise TypeError("cannot determine truth value of\n%s" % self)

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

TypeError: cannot determine truth value of ton <= t

TypeError:无法确定ton <= t的真值

As far as I understand, the error is due to the fact that both ton and t can be positive and negative. Is it correct? If I set positive integration limits for t the error doesn't disappear. How can I calculate the integral for the given piecewise function?

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

UPDATE: The updated version o the function, which works:

更新:功能的更新版本,其工作原理:

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

1 个解决方案

#1


2  

Piecewise Class

You need to use the sympy Piecewise class.

你需要使用sympy classwise。

As suggested in the comments:

正如评论中所建议的那样:

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

#1


2  

Piecewise Class

You need to use the sympy Piecewise class.

你需要使用sympy classwise。

As suggested in the comments:

正如评论中所建议的那样:

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