Search code examples
pythonsympyintegralabsolute-value

sympy: how to evaluate integral of absolute value


When I try to simplify the following integral in sympy, it will not evaluate, i.e. the output is $\int_{-1}^1 |z| dz$ while the output I expect is 1.

z = symbols('z', real=True)
a = integrate(abs(z), (z, -1, 1))
simplify(a)

Similar integral without the absolute value on z will evaluate.

How can I get sympy to evaluate this integral?


Solution

  • integrate already does all it can to evaluate an integral. If you get an Integral object back, that means it couldn't evaluate it. The only thing that might help is rewriting the integrand in a way that SymPy can recognize.

    Looking at this issue, it looks like a workaround is to rewrite it as Heaviside:

    In [201]: z = symbols('z', real=True)
    
    In [202]: a = integrate(abs(z).rewrite(Heaviside), (z, -1, 1))
    
    In [203]: a
    Out[203]: 1