6

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?

johnchen902
  • 9,531
  • 1
  • 27
  • 69
  • On coliru [it prints](http://coliru.stacked-crooked.com/a/0faa177acceb3caa) `first == second` for all four flags (using clang). – Shoe Jan 18 '14 at 06:55
  • With QtCreator 3.0.0, I got the same wrong result for MinGW 4.8 while MSVC 2012 32bits and 64 bits work fine in release mode. All Debug configurations work though. Strange. – Korchkidu Jan 18 '14 at 07:16
  • Also, printing first and second seems to change the results depending on whether they are printed before, or after the comparisons. – Korchkidu Jan 18 '14 at 07:24
  • 3
    Solution found: [Is this an g++ optimization bug?](http://stackoverflow.com/questions/7517588/is-this-an-g-optimization-bug) – johnchen902 Jan 18 '14 at 07:33

1 Answers1

5

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.

rullof
  • 7,124
  • 6
  • 27
  • 36