I know it's not "possible" to compare two real, but is it true for real which have denominator power of 2
Is equality of this king always return true
if( 3/4. == 6/8. ) {}
I know it's not "possible" to compare two real, but is it true for real which have denominator power of 2
Is equality of this king always return true
if( 3/4. == 6/8. ) {}
This kind of expression should always evaluate to true
, with a few caveats:
I can't quote anything that says it's guaranteed, but logically it should work because all IEE754 floating point numbers are represented as M * 2 ^ E, where M and E are both integers (and may be negative).
Hence 3 / 4.0
and 6 / 8.0
are both exactly equal to 3 * 2 ^ -2 and fully representable in IEE754 format.
Furthermore, given:
% cat test.cc
double three_quarters = 3 / 4.0;
double six_eighths = 6 / 8.0;
We get:
% c++ -S test.cc
% cat test.s
.globl _three_quarters
.data
.align 3
_three_quarters:
.long 0
.long 1072168960
.globl _six_eighths
.align 3
_six_eighths:
.long 0
.long 1072168960
Which shows that both expressions have been reduced (by the compiler) to the same constant value.
There is no requirement that C++ implementations use IEEE 754 floating point (or similar). But if yours does, this should work fine.
In general, whether floating-point equality comparison works depends not on the values, but how they were obtained.
e.g.
double v = 4/3.0; // inexact
double old_v = v;
some_func_that_might_change_its_argument(&v);
if (v == old_v) { ... }
is likely to work well despite the inexact value, while:
double v = 0;
for( int i = 0; i < 5; ++i ) v += 0.1;
if (v == 0.5) { ... }
is likely to fail even though both sides of the inequality can be expressed as a simple rational number where the denominator is a power of 2.