Simplifying nested Piecewise equations in sympy

Viewed 41

Say I have two piecewise equations (A(T) and B(T)), where the second references the first:

from sympy import *
T = symbols("T")

A = Piecewise((T + 1/T, (T >= 300) & (T < 700)), (log(T), (T >= 700) & (T < 900)), (T**9.0, (T >= 900) & (T < 6000)), (0, True))

B = Piecewise((A + 2*T, (T >= 300) & (T < 900)), (A + 3, (T >= 900) & (T < 6000)), (0, True))

If I just use simplify, I get A nested into B:

print(simplify(B))

Piecewise((Piecewise((3*T + 1/T, (T >= 300) & (T < 700)), (2*T + log(T), (T >= 700) & (T < 900)), (2*T + T**9.0, (T >= 900) & (T < 6000)), (2*T, True)), (T >= 300) & (T < 900)), (Piecewise((T + 3 + 1/T, (T >= 300) & (T < 700)), (log(T) + 3, (T >= 700) & (T < 900)), (T**9.0 + 3, (T >= 900) & (T < 6000))), (T >= 900) & (T < 6000)), (0, True))

Is there any way to get sympy to evaluate the expressions for the ranges and combine them? Ideally I would get something like:

Piecewise((3*T + 1/T, (T >= 300) & (T < 700)), (log(T) + 2*T, (T >= 700) & (T < 900)), (T**9.0 + 3, (T >= 900) & (T < 6000)), (0, True))
1 Answers

piecewise_fold will return a single Piecewise for you:

>>> simplify(piecewise_fold(B))
Piecewise(
(3*T + 1/T, (T >= 300) & (T < 700)),
(2*T + log(T), (T >= 700) & (T < 900)),
(2*T, (T >= 300) & (T < 900)),
(T**9.0 + 3, (T >= 900) & (T < 6000)),
(0, True))

Be careful with your exponents -- you might want to use 9 instead of 9.0.

Related