12

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?

2 Answers 2

13

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] 
Sign up to request clarification or add additional context in comments.

2 Comments

This works. However, I will be integrating the function over hundreds of thousands of small cells. Wouldn't this be too slow as it would involve calling a python function?
I don't know if integrate.quad will internally vectorize the function or not. I know integrate.quadrature does, but I got an error when I tried it on a double integral. You could always make the integration faster by increasing the tolerance. Or better yet, find an exact solution!
9

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

1 Comment

There must be a space between x and y in 'xy'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.