Lab 08: Numerical Integration


In this lab, we implement the different numerical integration methods studied in class.

  1. Finding the length of a curve
  2. Finding the area between the X-axis and a curve
  3. Finding the area between two curves


Finding the length of a curve

The idea is to divide the curve into small pieces and assume that these pieces are straight lines. Add up their lengths to get the length of the curve.

Let the curve extend along the X-axis from $a$ to $b$. We divide the extent between $a$ and $b$ into small pieces each of length $dx$. Let the corresponding position of the curve along the Y-axis be $y_a$ at $x=a$ and $y_b$ at $x=b$. After dividing the X-axis into small intervals $dx$, we have $$Values(X) = a, a+dx, a+2dx, a+3dx, \dots, a+(N-1)dx$$ Let us call these values $x_i$ where $x_i = a+(i-1)dx$ with $i=1, 2, 3, \ldots, N$. Similarly, the corresponding $y$ values are $y_i, i=1, 2, \ldots, N$.

The curve length is then given by $$ l = \sum_{i=1}^{N-1}\left[(x_{i+1}-x_i)\sqrt{1 + \left( \frac{y_{i+1}-y_i}{x_{i+1}-x_i}\right)^2}\,\right] $$

Write the code below for finding curve lengths.

In [2]:
import numpy as np
from math import sqrt
from matplotlib import pyplot as plt
np.set_printoptions(precision=2, suppress=True)
In [1]:
def curve_length(X, Y) :
    
    
    return length

Use the data from the cell below to test your code.

In [3]:
X = np.arange(0, 5, 0.25)
Y = 2.1 * X ** 2 - 5.7 * X + 9.81
plt.grid(True)
plt.plot(X, Y, 'xkcd:khaki')
plt.show()
In [4]:
### Solve the problem in this cell
length = 0.0

print('Length of the curve is: ', length)
Length of the curve is:  0.0


Finding the area between a curve and the X-axis

There are two main methods for finding the required areas.

  1. Trapezoidal Rule: $$ A = \frac{h}{2}(y_1 + 2y_2 + 2y_3 + \ldots + 2y_{N-1} + y_N)) $$ where $h$ is the difference between consecutive $x$ values, i.e. $x_{i+1} - x_i$.
  2. Simpsons Rule: $$ A = \frac{h}{3}(y_1 + 4y_2 + 2y_3 + 4y_4 + 2y_5 + \ldots + 4y_{N-1} + y_N) $$ where $h$ has the same meaning as before. Note however that this formula is only when the number of points is odd.
Implement the two methods in the cells below.

In [5]:
def area_trapezoid(X, Y) :
    area = 0.0
    
    return area
In [6]:
def area_simpson(X, Y) :
    area = 0.0
    
    return area

Try your code on the same example given for the length of the curve. The correct answer is $\approx 57.3$