Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Google Calculator Glitch, could float vs. double be a possible reason?

I did this Just for kicks (so, not exactly a question, i can see the downmodding happening already) but, in lieu of Google's newfound inability to do math correctly (check it! according to google 500,000,000,000,002 - 500,000,000,000,001 = 0), i figured i'd try the following in C to run a little theory.

int main()
{
   char* a = "399999999999999";
   char* b = "399999999999998";

   float da = atof(a);
   float db = atof(b);

   printf("%s - %s = %f\n", a, b, da-db);

   a = "500000000000002";
   b = "500000000000001";
   da = atof(a);
   db = atof(b);
   printf("%s - %s = %f\n", a, b, da-db);
}

When you run this program, you get the following

   399999999999999 - 399999999999998 = 0.000000
   500000000000002 - 500000000000001 = 0.000000

It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?

/mp

like image 287
mauriciopastrana Avatar asked Aug 25 '08 23:08

mauriciopastrana


3 Answers

For more of this kind of silliness see this nice article pertaining to Windows calculator.

When you change the insides, nobody notices

The innards of Calc - the arithmetic engine - was completely thrown away and rewritten from scratch. The standard IEEE floating point library was replaced with an arbitrary-precision arithmetic library. This was done after people kept writing ha-ha articles about how Calc couldn't do decimal arithmetic correctly, that for example computing 10.21 - 10.2 resulted in 0.0100000000000016.

like image 131
Frank Krueger Avatar answered Sep 19 '22 20:09

Frank Krueger


in C#, try (double.maxvalue == (double.maxvalue - 100)) , you'll get true ...

but thats what it is supposed to be:

http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

thinking about it, you have 64 bit representing a number greater than 2^64 (double.maxvalue), so inaccuracy is expected.

like image 28
gil Avatar answered Sep 21 '22 20:09

gil


It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?

No, you just defer the issue. doubles still exhibit the same issue, just with larger numbers.

like image 36
DrPizza Avatar answered Sep 19 '22 20:09

DrPizza