Integration Exercise 3

Imports


In [6]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate
from scipy.integrate import dblquad

2d polar integration

The 2d polar integral of a scalar function $f(r, \theta)$ is defined as:

$$ I(r_{max}) = \int_0^{r_{max}} \int_0^{2\pi} f(r, \theta) r dr d\theta $$

Write a function integrate_polar(f, rmax) that performs this integral numerically using scipy.integrate.dblquad.


In [45]:
def integrate_polar(f, rmax):
    """Integrate the function f(r, theta) over r=[0,rmax], theta=[0,2*np.pi]""" 
    integrand = lambda r,t: r*f(r,t)
    
    rlower = lambda y : 0
    rupper = lambda y : rmax
    
    I, err = integrate.dblquad(integrand, 0.0, 2*np.pi, rlower, rupper)
    return I

In [46]:
integrate_polar(lambda r,t: 1, 1.0), np.pi


Out[46]:
(3.141592653589793, 3.141592653589793)

In [47]:
assert np.allclose(integrate_polar(lambda r,t: 1, 1.0), np.pi)
assert np.allclose(integrate_polar(lambda r, t: np.exp(-r)*(np.cos(t)**2), np.inf), np.pi)