I have this code
#include <stdio.h>
#include <math.h>
static double const x = 665857;
static double const y = 470832;
int main(){
double z = x*x*x*x -y*y*y*y*4 - y*y*4;
printf("%f \n",z);
return 0;
}
The real solution of this is equation is 1. As already answered on a previous question by myself, this code fails because of catastrophic cancellation. However, now I’ve found an even more strange thing. It works if you use long longs, while, as far as I know, they have less range than doubles. Why?
long longhas less range, but more precision thandouble.However, that’s not what’s at work here. Your computation actually exceeds the range of
long longas well, but because of the way in which integer overflow is handled on your system, the correct result falls out anyway. (Note that the behavior of signed integer overflow is not pinned down by the C standard, but “usually” behaves as you see here).If you look instead at the intermediate result
x*x*x*x, you will see that if you compute it using double, it has a sensible value; not exact, but rounded and good enough for most purposes. However, if you compute it inlong long, you will find a number that appears at first to be absolutely bonkers, due to overflow.