AMath 585, Winter Quarter 2020 at the University of Washington. Developed by R.J. LeVeque and distributed under the BSD license. You are free to modify and use as you please, with attribution.
These notebooks are all available on Github.
This notebook demonstrates how the error behaves as $h = \Delta x$ is reduced in two different approximations to $u''(\bar x)$, the standard second-order accurate 3-point approximation and a fourth-order accurate centered 5-point approximation.
A table of errors is generated and then log-log plots of the error are compared with the behavior expected from the general expression for the truncation error of each method.
%matplotlib inline
from pylab import *
The python module fdstencil_functions.py
contains the functions that are defined in the notebook fdstencil.html, and was generated by exporting that notebook as Python and then editing out everything except the function definitions:
from fdstencil_functions import fdstencil
u = lambda x: sin(2*x)
u2 = lambda x: -4*sin(2*x)
u4 = lambda x: 16*sin(2*x)
u6 = lambda x: -64*sin(2*x)
x0 = 1.
u2_true = u2(x0)
h0 = 0.1
stencil_points = array([-1, 0, 1])
c = fdstencil(2, 0, stencil_points)
h_vals = []
errors = []
print('\n h error ')
for n in range(15):
h = h0 / 2**n
h_vals.append(h)
x = x0 + h*stencil_points
u2_approx = dot(c,u(x)) / h**2
error = abs(u2_approx - u2_true)
errors.append(error)
print('%10.8f %20.16f' % (h,error))
loglog(h_vals, errors, 'bx-', label='Observed errors')
xlim(1e-6,1)
ylim(1e-17,1)
grid(True)
xlabel('h = Delta x')
ylabel('abs(error)')
eref = 1/12. * array(h_vals)**2 * abs(u4(x0))
loglog(h_vals, eref, 'r-', label='Expected errors')
legend(loc='lower right')
x0 = 1.
u2_true = u2(x0)
h0 = 0.1
stencil_points = array([-2, -1, 0, 1, 2])
c = fdstencil(2, 0, stencil_points)
h_vals = []
errors = []
print('\n h error ')
for n in range(10):
h = h0 / 2**n
h_vals.append(h)
x = x0 + h*stencil_points
u2_approx = dot(c,u(x)) / h**2
error = abs(u2_approx - u2_true)
errors.append(error)
print('%10.8f %20.16f' % (h,error))
loglog(h_vals, errors, 'bx-', label='Observed errors')
xlim(1e-5,1)
ylim(1e-17,1)
grid(True)
xlabel('h = Delta x')
ylabel('abs(error)')
eref = 2/135. * array(h_vals)**4 * abs(u6(x0))
loglog(h_vals, eref, 'r-', label='Expected errors')
legend(loc='lower right')