Brian Zhang Larsen’s Blog

Oct 7
On floating-point numbers
  icon1 Brian Zhang Larsen | icon2 code | icon4 10 7th, 2006| icon3No Comments »

While skimming Steve McConnell’s Code Complete, second edition, the morning after the Chinese mid-autumn day (Alcohol was involved), I found an interesting point that I was not aware off. The preciseness of a 32-bit floating point is very disappointing (pardon the pun).

I wrote this simple piece of code in Java:

double sum=0.0;
for(int i=0;i<10;i++){
  sum+=0.1;
  System.out.println(sum);
}

The outcome of this is:

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

I think the Danish tax office has used to many floating-point numbers to calculate Vivians tax, since they already made 4 mistakes this year .

The point is, don't trust anyone :O