Wrong result when integrating piecewise function in sympy
I am starting to use sympy. I figured out the convolution, but the result was wrong:
This result is not correct: correct result
So what did I do wrong? I've used sympy to integrate piecewise functions before, no problem ...
Code:
from sympy import *
init_session()
f = lambda x: Piecewise( (1 , (x >= -1) & (x <= 1)) , (0 , True) )
Conv = lambda x: integrate( f(x-y)*f(y) , (y, -oo, +oo) )
source to share
There is nothing you did wrong. Sympy has a problem with the product of two piecewise expressions. By calling piecewise_fold(f(x-y)*f(y))
you can see that it cannot sort this product, leaving it as a nested slice construct.
Piecewise((Piecewise((1, And(x - y <= 1, x - y >= -1)), (0, True)), And(y <= 1, y >= -1)), (0, True))
The symbolic integration program runs this nested thing, which might be worth submitting an issue to GitHub .
Bypass
If you flatten this nesting piecewise by hand, the integration works correctly.
g = Piecewise((1, And(x-y <= 1, x-y >= -1, y <= 1, y >= -1)), (0, True)) integrate(g, (y, -oo, +oo))
outputs Min(1, x + 1) - Min(1, x + 1, Max(-1, x - 1))
which is correct , although perhaps not in the form you would expect.
source to share