I have MinGW GCC 4.8.1 and the following code:
#include <iostream>
#include <cmath>
double eval(int a, int b){
return std::sqrt(a) + std::sqrt(b);
}
int main(){
double first = eval(545, 331);
double second = eval(545, 331);
if(first < second)
std::cout << "first < second" << std::endl;
if(first == second)
std::cout << "first == second" << std::endl;
if(first > second)
std::cout << "first > second" << std::endl;
}
If compiled with -O0
, the program prints the expected result:
first == second
However, if compiled with -O1
, -O2
or -O3
, the program prints: (the result on ideone)
first < second
first == second
Why? How to fix it?
In x86 Architectures the precision of floating point is 80-bit but a double
has only 64-bit. And with GCC Optimization evaluating an expression resulting a floating number and storing it on a double
can result different values since the optimization changes how the floating number get adjusted to less precision.
To get the same result with different GCC Otimizations use -ffloat-store
option.