I know that comparing two doubles
is problematic if they are obtained from different calculations. But does this also hold in the case when one of them is a copy (in value) of the other. The following lines explain the scenario. If I have a problem like this,
double a,b;
a=randdouble();/*some double value*/
b=a;
Then,
Q1) Is the comparison a==b
always guaranteed to return true
in case of the C compiler (i have gcc 6.1.1
)?
Q2) Would the above answer remain the same if I am allocating variables a
and b
in heap memory using malloc
?
Q3) Would the above answers remain the same if I replace C compiler with a JAVA compiler (I am using Open JDK 1.7.0
) with the necessary syntax changes ofcourse.
Edit 1 : The numbers a
and b
are != NaN
Q1: The comparison is not guaranteed to evaluate to true, for the simple reason that NaN
compares unequal to itself. There might be other cases too, but NaN
is an obvious counterexample.
Q2: It makes no difference where the variables reside in memory.
Q3: I would expect Java to behave similarly.
This special case aside, I do believe the Standard does not give such a guarantee:
Imagine an ABI where double
expressions are evaluated and values are returned with 80 bit precision (Intel 80x87 stack) but stored as 64 bit IEEE-754 doubles. Even if randdouble()
is defined to return a double
, as opposed to long double
, its return value may be more precise than the value stored into a
or b
. Depending on how the compiler optimises the various expressions between the randdouble()
function call and the comparison a == b
, it may end up comparing the 80 bit precise return value with its close cousin obtained by converting to 64 bit and back to 80 bit. The comparison would fail if precision was lost in the conversion. I shall try and find a proper reference from the Standard to support this, but it seems plausible, and albeit whether a
or b
are local variables or stored on the heap might make a difference in the sequence of conversions performed, it would still be ill-advised to assume any guarantee for one or the other situations.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments