Double integral with variable bounds in python Scipy + sympy (?)

The complete math problem is here .

In short, I want to integrate a function with a double integral. The inner integral has boundaries 20

and x-2

, and the outer ones have boundaries 22

and 30

.

I know that with Scipy I can calculate the double integral with scipy.integrate.nquad

. I would like to do something like this:

def f(x, y):
    return (x ** 2 + y ** 2)
res = sp.integrate.nquad(f, [[22, 30], [20, x-2]])

      

Is it possible? Perhaps using also sympy

?

+3


source to share


2 answers


I solved it with sympy

:

from sympy import *

x, y = symbols("x y")
f = (x ** 2 + y ** 2)
res = integrate(f, (y, 20, x-2), (x, 22, 30))

      



Mainly sympy.integrate

able to deal with multiple integrations, also with variable boundaries.

+4


source


If you need numerical integration and sympy is not an option. Then you can try something like the following. It seems fast for this example, but I have a suspicion that you might run into problems in general, see how good it is for your use case. Perhaps this possibly imperfect answer will make someone post something better.

I am taking advantage of the fact that we can do the integration one by one, integrating y first to get a function of x, then integrating that.

from scipy.integrate import quad

def integrand(x, y): 
    return (x ** 2 + y ** 2)

def y_integral(x):
    # Note scipy will pass args as the second argument
    # we can fiddle it to work correctly, but by symmetry we don't need to here.
    return quad(integrand, 20, x-2, args=(x))[0]

      



We then use this y_integral function as the result function of the inner integral.

res = quad(y_integral, 22, 30) 
print res 

      

You can wrap this in a function if you use it regularly.

+2


source







All Articles