Search code examples
sumsympyintegralpiecewise

SymPy: how to integrate sum of two Piecewise functions without simplification?


I have a function that is a sum of 3 Piecewise functions:

from sympy import *
init_printing()
x = symbols('x')
M = Piecewise((13*x,x>=0),(0,True)) + Piecewise((-15*(x-2),x>=2),(0,True)) + Piecewise((-9*(x-4)**2/2,x>=4),(0,True))
M

Output: enter image description here

When I integrate this, I get:

C_1,EE,II=symbols('C_1,EE,II')
alpha=-1/(EE*II)*(integrate(M,x)+C_1)
alpha

Output: enter image description here

But I would like the result to be in a form that shows the integral grouped the same way as M, so in 3 groups. Like this, I would hope seeing something like "-9(x-4)^3/6" in the last part.
Is this possible, without having to calculate the integrals for each of the 3 parts of M separately?
I tried to use something like M.piecewise_integrate(x), but that doesn't seem to work on M directly, probably since it is a sum of Piecewises?


Solution

  • One way to achieve that is by using the linearity of integrals: you can integrate each addend of M separately, and adding the results together.

    Add(*[integrate(a, x) for a in M.args])
    

    Then you add the constant and multiply by your factors.