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.

DSM
  • 342,061
  • 65
  • 592
  • 494
Tim D
  • 1,645
  • 1
  • 25
  • 46
  • Why don't you just evaluate the indefinite integral at the boundaries of your integration interval and subtract those two values from each other? – David Zwicker Feb 07 '13 at 17:13
  • 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. – Tim D Feb 07 '13 at 18:10
  • 1
    @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). – asmeurer Feb 08 '13 at 17:56

1 Answers1

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).

Krastanov
  • 6,479
  • 3
  • 29
  • 42
  • 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. – asmeurer Feb 08 '13 at 17:54