Integration Exercise 3

Imports


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

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 drd\theta $$

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


In [15]:
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)
    rmin = 0
    rmax = rmax

    tmin = lambda r : 0
    tmax = lambda r : 2*np.pi
    
    I = integrate.dblquad(integrand, rmin, rmax, tmin, tmax)
    return I

In [16]:
integrate_polar(lambda r,t: 1, 1.0) #This is returning 2pi instead of pi and I don't know why


Out[16]:
(19.739208802178712, 2.1914924100062363e-13)

In [17]:
integrate_polar(lambda r, t: np.exp(-r)*(np.cos(t)**2), np.inf) #this doesn't equal pi either


Out[17]:
(255.81538589533068, 112.64261334751413)

In [18]:
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)


---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-18-6f12576707cd> in <module>()
----> 1 assert np.allclose(integrate_polar(lambda r,t: 1, 1.0), np.pi)
      2 assert np.allclose(integrate_polar(lambda r, t: np.exp(-r)*(np.cos(t)**2), np.inf), np.pi)

AssertionError: 

In [ ]: