Tanja Tanja - 5 months ago 54
Python Question

Python: Piecewise function integration error: "TypeError: cannot determine truth value of ..."

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)

TypeError: cannot determine truth value of
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?

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

Answer

Piecewise Class

You need to use the sympy Piecewise class.

As suggested in the comments:

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