Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparation of sum of square roots [duplicate]

Tags:

c++

sqrt

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?

like image 597
johnchen902 Avatar asked Jan 18 '14 06:01

johnchen902


People also ask

What happens when you multiply two identical square roots?

Finding the product of roots To multiply two square roots, we just multiply the radicands and put the product under a radical sign. That is, the product of two square roots is equal to the square root of the product of the radicands.

How do you compare two roots?

For comparing them, we should always keep in mind that if square or cube roots of two numbers ('a' and 'b') are to be compared, such that 'a' is greater than 'b', then a2 will be greater than b2 and a3 will be greater than b3 and so on, i.e., nth power of 'a' will be greater than nth power of 'b'.


1 Answers

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.

like image 199
rullof Avatar answered Oct 04 '22 07:10

rullof