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

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


In [4]:
def integrate_polar(f, rmax):
    """Integrate the function f(r, theta) over r=[0,rmax], theta=[0,2*np.pi]"""
    integrate=lambda r,t:r*f(r,t)
    theta1=0.0
    theta2=2*np.pi
    r1=lambda t:0.0
    r2=lambda t:rmax
    res=integrate.dblquad(integrate,theta1,theta2,r1,r2)
    return res[0]

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


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-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)

<ipython-input-4-9b420107c1dc> in integrate_polar(f, rmax)
      6     r1=lambda t:0.0
      7     r2=lambda t:rmax
----> 8     res=integrate.dblquad(integrate,theta1,theta2,r1,r2)
      9     return res[0]

AttributeError: 'function' object has no attribute 'dblquad'

In [ ]: