Integration

There are several ways to evaluate integrals with limits numerically. One way is to use scipy's "quad" function. Let's try this out on the integral $$\int_0^1 \sqrt{\frac{x}{2-x}} dx.$$

Analytic Solution

The analytic solution is found if we make the substitution $x = 2\sin^2 \theta$ so $dx = 4 \cos \theta \sin \theta d\theta$. This also changes the limits from 0 to 1 to 0 to $\pi/4$. Now, we can evaluate the integral using standard tricks \begin{align} \int_0^1 \sqrt{\frac{x}{2-x}} dx &= \int_0^{\pi/4} \sqrt{ \frac{2 \sin^2 \theta}{2 - 2 \sin^2 \theta} } 4 \cos \theta \sin \theta d\theta \\ &= \int_0^{\pi/4} \sin^2 \theta d\theta \\ &= 2 \int_0^{\pi/4} (1-\cos 2 \theta) d\theta \\ &= 2 \left[ 1 - \frac{\sin 2\theta}{2}\right]_0^{\pi/4} \\ &= \frac{\pi}{2} - 1. \end{align} Now let's see how to find this numerically.

Using scipy's "quad" function

Monte-Carlo Integration

Another (more fun) method of numerical integration is the Monte-Carlo method. This involves generating a load of random numbers in a box that you know the area of. You then count how many of the points sit in the red area of the curve (this is what we're trying to find), $N_I$.
Dividing this by the total number of points you've generated $N_I/N$ gives you something like the probability that a point generated inside the box you've chosen will be in the area you're trying to find. Multiplying this probability by the total area of the box $A$ gives an approximaion to the integral, $I \approx A N_I / N$. More information and ways to improve this approximation can be found in [1].

In the cells below we apply this method to the integral we were considering at the start of this notebook. We also see how the error of the Monte-Carlo method depends on the number of sample points used. It also depends on how the sample points you generate are distributed, but this is another topic.

References:

  1. Press, WH; Teukolsky, SA; Vetterling, WT; Flannery, BP (2007). Numerical Recipes: The Art of Scientific Computing (3rd ed.). New York: Cambridge University Press