Some surprising remarks about computers accuracy

by Paolo Sirtoli (sirtoli@uninetcom.it)
Examples excerpts from the book "Astronomical algorithms"
by Jean Meeus, Willmann-Bell Inc.

 

Java works in compliance with IEEE 754 specification about floating point representation:

   
number of bit allocated for ...
sign
exponent
mantissa
single precision (float)
32 bit
1
8
23
double precision (double)
64 bit
1
11
52

More about IEEE 745 standard

 

Example 1: significant digits.
Here you are a simple routine that determines the number of significant digits

 

Example 2: trigonometric functions.
Previous example concerns simple arithmetics but not covers trigonometric functions, that are very important in astronomical calculus. Some computer has a high internal precision, but sometimes trigonometric functions are given with much less correct decimals. To know if our computer has a good precision, let's do a couple of calculus.
The correct value for
sin(0,61) is 0,57286746010048 and 4*arctan(1) must be equal to pi=3,14159265358979

 

Example 3: series.
Let's try to calculate first 27 terms of that serie:

x0=1.0000001
xn+1=xn^2

The correct value must be 674530,4740 (if the result is infinity press "reload")

If the result is not correct, don't worry: on most computers x=674530,4755!

Let's try now a cycle:

for (i=0;i<=100;i+=0.1) x=j;

x takes the all values from 0 to 100 with a step of 0,1 and the last value must be exactly 100, but my computer gives 99,9999999999986, wich can have a disastrous consequence in some applications.

 

Another cycle starts with x=1/3; and replaces x by itself 24 times in a creative way,

for (i=1;i<=30;i++) x=(9*x+1)*x-1;

so x must be ever 1/3, but is not so (if the result is infinity press "reload"):

An important remark about Java language: the instruction

double x=1/3;

to initialize our cycle is not correct because the division between integers give a result that is an integer too, so in this example x=0!
Thus we must declare x as double

x=1./3.;

 

Example 4: elementary math ... or not so.
Tell me the result: 2 + 0,2 + 0,2 + 0,2 + 0,2 + 0,2 - 3 = ?
What tells your computer?

And if we collect some terms and calculate 2 + 5 * (0,2) - 3= ?
The result now is ...

Some surprise comes from this simple calculus: x = int(3 * (1/3)).
Naturally the correct result is 1, but some computers does not agree!

 

If you want, you can check out the source of above applets.