4

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?

Brian
  • 3,453
  • 2
  • 27
  • 39
  • 3
    My impression is that sympy's simplification is not yet as good as it could be. There are also several other simplification methods in simpy (trigsimp, ratsimp, powsimp, combsimp,...) but I would not count on them being able to simplify the integral. Sometimes simplify fails even though it looks very simple to humna. You can use in this situation also the .evalf() method. Have a look also here: http://docs.sympy.org/latest/tutorial/simplification.html – dnalow Sep 19 '16 at 08:33

2 Answers2

4

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
asmeurer
  • 86,894
  • 26
  • 169
  • 240
-3

I believe you should use Sympy's built in Abs() function.

Enjoy!

et3rn1ty
  • 40
  • 2
  • Hello, thank you for your response. Unfortunately, I have already tried the built-in `sympy.Abs` function as well without success. Also, I believe `abs` and `sympy.Abs` are the same function. – Brian Sep 19 '16 at 08:18
  • 1
    abs is correct, since it just calls the `z.__abs__` method which is defined differently for each object (floats or sympy symbols etc..) – dnalow Sep 19 '16 at 08:30