Page 46 - Applied Numerical Methods Using MATLAB
P. 46
COMPUTER ERRORS VERSUS HUMAN MISTAKES 35
>>nm125_1
y^-20/e^-20x = 0.000000000000000e+000
(y/e^x)^-20 = 4.920700930263814e-008
y^-19/e^-19x = 1.141367814854768e-007
(y/e^x)^-19 = 1.141367814854769e-007
y^19/e^19x = 8.761417546430845e+006
(y/e^x)^19 = 8.761417546430843e+006
y^20/e^20x = NaN
(y/e^x)^20 = 2.032230802424294e+007
Second, in order to prevent ‘loss of significance’, it is important to avoid a
‘bad subtraction’ (Section 1.2.2)—that is, a subtraction of a number from another
number having almost equal value. Let us consider a simple problem of finding
2
the roots of a second-order equation ax + bx + c = 0 by using the quadratic
formula
√ √
2
2
−b + b − 4ac −b − b − 4ac
x 1 = , x 2 = (1.2.17)
2a 2a
2
Let |4ac|≺ b . Then, depending on the sign of b, a “bad subtraction” may be
encountered when we try to find x 1 or x 2 , which is the smaller one of the two
roots. This implies that it is safe from the “loss of significance” to compute the
root having the larger absolute value first and then obtain the other root by using
the relation (between the roots and the coefficients) x 1 x 2 = c/a.
For another instance, we consider the following two formulas, which are ana-
lytically the same, but numerically different:
2
1 − cos x sin x
f 1 (x) = , f 2 (x) = (1.2.18)
2
x 2 x (1 + cos x)
It is safe to use f 1 (x) for x ≈ π since the term (1 + cos x) in f 2 (x) is a ‘bad sub-
traction’, while it is safe to use f 2 (x) for x ≈ 0 since the term (1 − cos x) in f 1 (x)
is a ‘bad subtraction’. Let’s run the following MATLAB program “nm125_2.m”
to confirm this. Below is the running result. This implies that we might use some
formulas to avoid a ‘bad subtraction’.
%nm125_2: round-off error test
f1 = inline(’(1 - cos(x))/x/x’,’x’);
f2 = inline(’sin(x)*sin(x)/x/x/(1 + cos(x))’,’x’);
for k = 0:1
x = k*pi; tmp = 1;
for k1 = 1:8
tmp = tmp*0.1; x1 = x + tmp;
fprintf(’At x = %10.8f, ’, x1)
fprintf(’f1(x) = %18.12e; f2(x) = %18.12e’, f1(x1),f2(x1));
end
end