SymPy - apply limits to an indefinite integral
Asked Answered
G

1

5

In SymPy, is it possible to apply limits to an indefinite integral and evaluate it?

import sympy
from sympy.abc import theta

y = sympy.sin(theta)

Y_indef = sympy.Integral(y)
Y_def = sympy.Integral(y, (theta, 0, sympy.pi / 2))

Y_def.evalf() produces a number.

I'm looking for something like Y_indef.evalf((theta, 0, sympy.pi/2)) to get the same answer.

Gomez answered 7/2, 2013 at 16:21 Comment(3)
Why don't you just evaluate the indefinite integral at the boundaries of your integration interval and subtract those two values from each other?Discus
I guess I'm more trying to figure out the difference between the Y_indef and Y_def objects above, and is it possible to do something to Y_indef to make it behave like Y_def.Gomez
@DavidZwicker that naive approach will not work in general. If there are poles in the integration domain, you'll get the wrong answer. Also, quite often the definite integral can be computed but the indefinite integral cannot (and this is definitely true if you are only interested in a numerical evaluation).Ferrante
R
7

I do not know of a direct way, however you can extract the information from Y_indef in order to create a definite integral:

>>> indef = Integral(x)
>>> to_be_integrated, (free_var,) = indef.args
>>> definite = Integral(to_be_integrated, (free_var, 1, 2))

.args is a general attribute containing anything needed to construct most SymPy objects.

Edit: To address the comments to the questions.

  1. SymPy may succeed evaluating definite integral and at the same time fail to solve their indefinite version. This is due to the existence of additional algorithms to be applied to definite integrals.

  2. Both definite and indefinite integrals are instances of the same class. The only difference is what they contain in their .args. The need for different classes is not yet felt, given that SymPy mostly uses Integral as a flag to say that it can not solve the integral (i.e. the integrate function returns Integral when all of the implemented algorithms fail).

Risner answered 7/2, 2013 at 22:33 Comment(1)
This is correct. The only way to do this is to create a new Integral and evaluate that, which can be done with a simple helper function.Ferrante

© 2022 - 2024 — McMap. All rights reserved.