Page 38 - Applied Numerical Methods Using MATLAB
P. 38
COMPUTER ERRORS VERSUS HUMAN MISTAKES 27
Example 8. while Loops to Find the Minimum/Maximum Positive Numbers
The following program “nm119 8.m” contains three while loops. In the first
one, x= 1 continues to be divided by 2 until just before reaching zero, and it
will hopefully end up with the smallest positive number that can be represented
in MATLAB. In the second one, x=1 continues to be multiplied by 2 until just
before reaching inf (the infinity defined in MATLAB), and seemingly it will get
the largest positive number (x_max0) that can be represented in MATLAB. But,
while this number reaches or may exceed inf if multiplied by 2 once more, it still
is not the largest number in MATLAB (slightly less than inf)thatwewantto
n
find. How about multiplying x_max0 by (2 − 1/2 )? In the third while loop, the
temporary variable tmp starting with the initial value of 1 continues to be divided
by 2 until just before x_max0*(2-tmp) reaches inf, and apparently it will end
up with the largest positive number (x_max) that can be represented in MATLAB.
%nm119_8: example of while loops
x=1;k1=0;
while x/2 > 0
x = x/2; k1 = k1 + 1;
end
k1, x_min = x;
fprintf(’x_min is %20.18e\n’,x_min)
x=1;k2=0;
while 2*x < inf
x = x*2; k2 = k2+1;
end
k2, x_max0 = x;
tmp=1;k3=0;
while x_max0*(2-tmp/2) < inf
tmp = tmp/2; k3 = k3+1;
end
k3, x_max = x_max0*(2-tmp);
fprintf(’x_max is %20.18e\n’,x_max)
format long e
x_min,-x_min,x_max,-x_max
format hex
x_min,-x_min,x_max,-x_max
format short
1.2 COMPUTER ERRORS VERSUS HUMAN MISTAKES
Digital systems like calculators and computers hardly make a mistake, since they
follow the programmed order faithfully. Nonetheless, we often encounter some
numerical errors in the computing results made by digital systems, mostly coming
from representing the numbers in finite bits, which is an intrinsic limitation of dig-
ital world. If you let the computer compute something without considering what
is called the finite-word-length effect, you might come across a weird answer. In