Use MATLAB to make a table of the error of the three-point centered-difference formula for f(0), where f(x) = sin(x) - cos(x), with h = 10^(-1), ..., 10^(-12), as in the table in Section 5.1.2. Draw a plot of the results. Does the minimum error correspond to the theoretical expectation?
Formula:
Three-point centered-difference formula for second derivative:
f(x + h) - 2f(x) + f(x - h) / h^2 = f''(x) + O(h^2)
5.1.2 Rounding error:
So far, all of this chapter's formulas break the rule from Chapter 0 that advises against subtracting nearly equal numbers. This is the greatest difficulty with numerical differentiation, but it is essentially impossible to avoid. To understand the problem better, consider the following example:
EXAMPLE 5.3:
Approximate the derivative of f(x) = e^x at x = 0. The two-point formula (5.4) gives e^(x+h) - e^x / h, and the three-point formula (5.7) yields e^(x+h) - e^(x-h) / 2h. The results of these formulas for x = 0 and a wide range of increment size h, along with errors compared with the correct value e^0 = 1, are given in the following table:
Formula (5.9) Error Formula (5.10) Error
10^(-1) 1.05170918075648 0.05170918075648 1.00166750019844 0.00166750019844
10^(-2) 1.00501670841679 -0.00501670841679 1.00001666674999 -0.00001666674999
10^(-3) 1.00050016670838 -0.00050016670838 1.00000016666668 -0.00001666666668
10^(-4) 1.00005000166714 -0.00005000166714 1.00000000166689 -0.00000000166689
10^(-5) 1.00000500000696 -0.00000500000696 1.00000000001210 -0.00000000001210
10^(-6) 1.00000049996218 -0.00000049996218 0.99999999997324 0.00000000002676
10^(-7) 1.00000004943368 -0.00000004943368 0.99999999947364 0.00000000052636
10^(-8) 0.99999999392253 0.00000000607747 0.99999999392253 0.00000000607747
10^(-9) 1.00000008274037 -0.00000008274037 1.00000002722922 -0.00000002722922