Comparation of sum of square roots [duplicate]
Asked Answered
S

1

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?

Sublimity answered 18/1, 2014 at 6:49 Comment(4)
On coliru it prints first == second for all four flags (using clang).Buatti
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.Sadism
Also, printing first and second seems to change the results depending on whether they are printed before, or after the comparisons.Sadism
Solution found: Is this an g++ optimization bug?Sublimity
P
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.

Prehuman answered 18/1, 2014 at 8:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.