Section 12.5 Examples and questions
These are additional examples for reviewing the topic we have covered. When reading each example, try to find your own solution before clicking “Answer”. There are also questions for reviewing the concepts of this section.
Example 12.5.1. Rewrite a formula to avoid the loss of significance.
The formula \((1-\cos(x))/x^2\) is prone to loss of significance when \(x\) is close to \(0\text{.}\) Rewrite it in a mathematically equivalent way which avoids this issue. Compare the performance of both formulas in Matlab with \(x = 10^{-9}\text{.}\)
The issue is that \(\cos x\) is close to \(1\) and we subtract it from \(1\text{.}\) The identity
can be used to avoid this issue. According to it,
There is no loss of significance in the formula on the right. Compare in Matlab:
f = @(x) (1-cos(x))/x^2; g = @(x) sin(x)^2/(x^2*(1+cos(x))); disp(f(1e-9)) disp(g(1e-9))
The first formula produces \(0\text{,}\) the second produces \(0.5\text{.}\) The second value is correct. Indeed,
Example 12.5.2. Compare the accuracy of three approximations to \(f'\).
Consider the function \(f(x) = \sin x\) on the interval \([0, 5]\text{.}\) Compare the accuracy of the three approximations to its derivative ((12.1.1), (12.3.1), (12.4.4)) by plotting the error for each of them on the logarithmic scale (with semilogy
). Use \(h = 0.1\text{.}\)
f = @(x) sin(x); fp = @(x) cos(x); x = linspace(0, 5, 500); h = 0.1; orig = (f(x+h) - f(x))/h; symm = (f(x+h) - f(x-h))/(2*h); extr = 2*(f(x+h) - f(x-h))/(3*h) - (f(x+2*h) - f(x-2*h))/(12*h); exact = fp(x); semilogy(x, abs(orig-exact), x, abs(symm-exact), x, abs(extr-exact)) legend('original', 'symmetric', 'extrapolated')
The result indicates that the error is about \(10^{-1}\) for the original formula (from the definition of derivative), about \(10^{-3}\) for the symmetric formula, and about \(10^{-6}\) for the extrapolated formula.
Question 12.5.3. What makes the error smaller in some places?
As we see in Example 12.5.2, the size of error suddently becomes much smaller in certain parts of the interval. What is special about those places that makes the approximation more accurate?
HintRecall the connection with Taylor series: the error term involves derivatives of higher order.