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?
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.
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'.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With