Reputation: 761
I am starting to use sympy. I computed a convolution, but the result was not correct:
This result is wrong: The correct result is
So what did I do wrong? I had used sympy to integrate piecewise fucntions before, with no problems...
The 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) )
Upvotes: 3
Views: 1879
Reputation:
There is nothing that you did wrong. It's Sympy having an issue with the product of two piecewise expressions. By calling piecewise_fold(f(x-y)*f(y))
you can see that it does not manage to sort this product out, leaving it as a nested Piecewise construction.
Piecewise((Piecewise((1, And(x - y <= 1, x - y >= -1)), (0, True)), And(y <= 1, y >= -1)), (0, True))
The symbolic integration routine trips up on this nested thing, which may be worth filing an issue on GitHub.
If you flatten this nested 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 one would expect.
Upvotes: 1