Section 8.4 Trapezoidal rule (n=1)
In this case we are using a 2-points interpolation in [a,b]. These two points must be the endpoints x0=a and x1=b. The interpolating polynomial will have degree 1. The Lagrange polynomials are
L0(x)=x−x1x0−x1,L1(x)=x−x0x1−x0
and the corresponding weights are
w0=∫bax−ab−adx=b−a2=w1.
Hence the Trapezoidal rule formula gives
Q1(f,[a,b])=f(a)+f(b)2(b−a).
Local error. From the Newton-Cotes error formula, we get that
|∫baf(x)dx−Q1(f,[a,b])|≤(b−a)32max[a,b]|f″(x)|∫10s(s−1)ds=(b−a)312max[a,b]|f″(x)|.
As usual, this shows that this approximation can be lousy unless b−a≪1.
Trapezoidal rule formula. We bypass as usual the error problem above by subdiving the interval as shown in the previous two sections. In this case, we get that
Q1,h(f,[a,b])=hn−1∑k=0f(xk)+f(xk+1)2
Trapezoidal rule error. From the error formula above, we get that
|∫xk+1xkf(x)dx−Q1(f,[xk,xk+1])|≤h312max[a,b]|f″(x)|
and therefore
|∫baf(x)dx−Q1,h(f,[a,b])|≤h2b−a12max[a,b]|f″(x)|.
Convergence Speed. The formula above shows that the truncation error of the Trapezoidal rule is O(h2), like for the Midpoint rule. Below we visualize this scaling law by evaluating the error in the computation of ∫20sin(x)dx with h=10−j,1≤j≤7. As in the Midpoint case, the round-off error effects shows already at h=10−7 and the error achievable on this integral is about h=10−13. xxxxxxxxxx
from numpy import linspace,array,frompyfunc,sin,zeros
from matplotlib import pyplot as plt
n=9; a=0.; b=2.; N=1
s = zeros(n); err = zeros(n)
for i in range(n):
h = (b-a)/N
x = linspace(a,b,N+1) # these are the x_i
t = ( sin(x[:-1]) + sin(x[1:]) ) / 2; # average of sine on endpoints
s[i] = sum(h*t) # this is the integral
err[i] = abs(1-cos(2)-s[i]) # and this is the actual error
N *= 10
I = range(n)
h = array([(b-a)/10**i for i in I])
plt.clf()
plt.loglog(h,err[I],label=r'$y=error(h)$')
plt.loglog(h,h**2,label=r'$y=h^2$')
plt.xlabel('log h')
plt.ylabel('log y')
plt.legend()
plt.show()