Trapezoidal rule to approximate integrals
In this article we approximate integrals by the trapezoidal rule.
- One dimensional integrals
Let [math] [a,b] [/math] be an interval and [math] f:[a,b]\to \mathbb{R} [/math] a real function. We want to approximate the integral [math] \int_a^bf(u) \; du [/math].
Consider a partition of the interval [math] [a,b] [/math] in [math] N [/math] equal subintervals of length [math] h=\frac{b-a}{N} [/math], given by [math] u_n=a+nh, [/math] where [math] n=0,1,...,N [/math]. The trapezoidal rule is as follows:
- [math] \int_a^b f(u) \; du \sim h\frac12 f(u_0)+h\sum_{i=1}^{N-1}f(u_i)+h\frac12 f(u_N) [/math]
that can be written as
- [math] \int_a^b f(u) \; du \sim h\sum_{i=0}^{N}w_if(u_i)=hw^t*f, [/math]
where [math] w_i [/math] are the components of the weight column vector [math] w=(1/2,1,1,...,1,1,1/2)^t [/math] and [math] f [/math] is the column vector [math] f=(f(u_0),f(u_1),...,f(u_N))^t [/math].
Example: En Matlab/Octave vamos a aproximar la integral de [math] e^{-x^2} [/math] en [math] [-1,1] [/math] con [math] h=0.1 [/math]
N=200; %Number of points
a=-1; b=1; %Extremes of the interval
h=(b-a)/N;
u=a:h:b; %coordinates of the partition
f=exp(-u.^2); %function
w=ones(1,N+1); %weights vector
w(1)=1/2; w(N+1)=1/2;
result=w*f' % result