Skip to main content

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.

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{.}\)

Solution

The issue is that \(\cos x\) is close to \(1\) and we subtract it from \(1\text{.}\) The identity

\begin{equation*} (1-\cos x)(1+\cos x) = 1-\cos^2 x = \sin^2 x \end{equation*}

can be used to avoid this issue. According to it,

\begin{equation*} \frac{1-\cos(x)}{x^2} = \frac{\sin^2(x)}{x^2(1+\cos x)} \end{equation*}

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,

\begin{equation*} \frac{1-\cos(x)}{x^2} \to \frac12 \quad \text{as } x\to 0 \end{equation*}

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{.}\)

Solution
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.

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?

Hint

Recall the connection with Taylor series: the error term involves derivatives of higher order.