Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D integrals in SciPy

I am trying to integrate a multivariable function in SciPy over a 2D area. What would be the equivalent of the following Mathematica code?

In[1]:= F[x_, y_] := Cos[x] + Cos[y] 

In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]}]

Out[2]= 0

Looking at the SciPy documentation I could only find support for one-dimensional quadrature. Is there a way to do multidimensional integrals in SciPy?

like image 569
D R Avatar asked Mar 03 '10 02:03

D R


People also ask

What is a single integration function in SciPy?

Single Integrals. The Quad function is the workhorse of SciPy’s integration functions. Numerical integration is sometimes called quadrature, hence the name. It is normally the default choice for performing single integrals of a function f(x) over a given fixed range from a to b.

How to get the double integration of a polynomial using SciPy?

In this example we can see that by using scipy.integrate.dblquad () method, we are able to get the double integration of a polynomial from limit a to b by using this method.

What is the latest version of SciPy for differential equation integration?

This is documentation for an old release of SciPy (version 0.18.1). Read this page in the documentation of the latest stable release (version 1.7.1). The scipy.integrate sub-package provides several integration techniques including an ordinary differential equation integrator.

What is an example of a double integral method in Python?

As an example, let us perform the double integral method. We define the functions f, g, and h, using the lambda expressions. Note that even if g and h are constants, as they may be in many cases, they must be defined as functions, as we have done here for the lower limit. The above program will generate the following output.


2 Answers

I think it would work something like this:

def func(x,y):
    return cos(x) + cos(y)

def func2(y, a, b):
    return integrate.quad(func, a, b, args=(y,))[0]

print integrate.quad(func2, -pi/2, pi/2, args=(-pi/2, pi/2))[0]

Wolfram|Alpha agrees

edit: I just discovered dblquad which seems to do exactly what you want:

print integrate.dblquad(func, -pi/2, pi/2, lambda x:-pi/2, lambda x:pi/2)[0]
like image 75
Paul Avatar answered Sep 19 '22 17:09

Paul


If you want to do symbolic integration, have a look at sympy (code.google.com/p/sympy):

import sympy as s
x, y = s.symbols('x, y')
expr = s.cos(x) + s.sin(y)
expr.integrate((x, -s.pi, s.pi), (y, -s.pi, s.pi))
like image 30
Stefan van der Walt Avatar answered Sep 21 '22 17:09

Stefan van der Walt