This page was generated from notebooks/L5/2_integration.ipynb.
You can directly download the pdf-version of this page using the link below.
download
Numerical Integration#
Our second topic today will be about numerical integration, which is useful in determining of course the integrals of functions at certain positions. Here we will only refer to 3 different methods with increasing accuracy.
[2]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_forsmat = 'retina'
plt.rcParams.update({'font.size': 10,
'lines.linewidth': 1,
'lines.markersize': 5,
'axes.labelsize': 10,
'xtick.labelsize' : 9,
'ytick.labelsize' : 9,
'legend.fontsize' : 8,
'contour.linewidth' : 1,
'xtick.top' : True,
'xtick.direction' : 'in',
'ytick.right' : True,
'ytick.direction' : 'in',
'figure.figsize': (4, 3),
'figure.dpi': 150 })
Box method#
The simplest method for the numerical integration of a function
So lets write a function for that:
[3]:
def f(x):
return(x)
[4]:
def int_box(f,a,b,N):
x=np.linspace(a,b,N)
y=f(x)
return(np.sum((x[1]-x[0])*y))
[7]:
int_box(f,0,1,100)
[7]:
0.5050505050505051
[11]:
acc=[]
for N in range(10,10000,100):
acc.append(int_box(f,0,1,N))
plt.loglog(range(10,10000,100),np.array(acc)-0.5)
plt.show()

Trapezoid method#
The trapezoid method is taking the next step of function approximation in the interval
which is actually the same as
We will use the first formula for coding it, and you may try the second yourself.
[12]:
def int_trap(f,a,b,N):
x=np.linspace(a,b,N)
y=f(x)
return(np.sum((y[1:]+y[:-1])*(x[1]-x[0])/2))
[13]:
## value from the box method
int_box(f,0,1,100)
[13]:
0.5050505050505051
[14]:
## value from the tapez method
int_trap(f,0,1,100)
[14]:
0.5000000000000001
The trapez method therefore seems to give a better accuracy than the box method for the same number of steps.
Simpson method#
The Simpson method now continues with approximating the function now with a collection of parabolas.
where the function
where the
After some extensive algebra, which we do not want to do in detail, we arrive at
as a simple formula on how to calculate the integral of a function using the Simpson method. Note that this method requires N being an odd number, which generates an even number of slices. There is a correction for odd number of slices, which we do not consider here.
[15]:
def int_simp(f,a,b,N):
x=np.linspace(a,b,N)
y=f(x)
return(np.sum((y[0:-2:2]+4*y[1:-1:2]+y[2::2])*(x[1]-x[0])/3))
[16]:
## value from the tapez method
int_trap(f,0,1,100)
[16]:
0.5000000000000001
[17]:
## value from the box method
int_box(f,0,1,100)
[17]:
0.5050505050505051
[18]:
## value from the simpson method
## take care, N needs to be odd
int_simp(f,0,1,99)
[18]:
0.5
It turns out, that the Simpson rule is indeed the best among the three methods we have considered. The error is the box method goes as