1 – 0.8 – 0.2 = ?

That seems to be a silly question, but still, let us solve it. I know that, you know that, I know the answer :-), but for the sake of a small discussion let us ask Google, msn, altavista. What, is this the answer? 1 – 0.8 – 0.2 = -5.551115×10^-17 There seems to be wrong somewhere.

Is that a bug with all of them? Let me quickly write a perl program to calculate 1 – 0.8 – 0.2. Here is the program.
$a = 1.0 – 0.8 – 0.2;
print $a;
The same answer. I knew it, perl already got a reputation for being “Pathologically Eclectic Rubbish Language”, how can I trust the result.
Now a days everybody is talking about java let me write a java program and findout. Here is the program.

public class SimpleCalc
{
public static void main(String[] arg){
double a = 1.0 – 0.8 – 0.2;
System.out.print(a);
}
}

The same answer again. I did not expect this from java? Did java take a coffee break? or all of a sudden Something happened to these computers. Why is this simple calculation being wrongly calculated by software? If this happens how can financial software gain credibility with users? How can I safely write some code like (a-b-c) == d and be sure that the equality is correclty compared. There is something more about this floating point calculations that one should know about?.

Let me write a c program to find this. Here is the program
main() {
double c = 1 – 0.8 – 0.2 ;
printf(“%f”, c);
}
The result is -0.000, but thats fine in c 0 is treated as -0 or 0.
Hmnn now Iam happy. Let me gain more support, I will ask the Database. Here is the sql.
select 1 – 0.8 – 0.2 from dual;
This result is now perfect. It seems that each language has a different way of doing floating point arithmetic.
Here are some good links that expose the problems underlying the floating point computations.
1. What Every Computer Scientist should know about Floating point Arthemetic.
2. Floating Point arithmetic.
3. How to correct rounding errors in Floating point Arithmetic.
4. Floating Point Basics.
But the question still remains. How come C program gave correct results?. Thats because we were lucky this time. C probably has a better rounding mechanism. Try this code.

for (float index = 0.0; index != 1.0; index += 0.1)
printf(“%f\n”, index);

So be cautious when using the floating point arithmetic in programs.
I want to conclude that its a bug if calculators show this kind of results and hence all the google, msn and altavista calculators should probably fix the Bug.

Advertisements

About this entry