c++ - Floating Point, how much can I trust less than / greater than comparisons? -
let's have 2 floating point numbers, , want compare them. if 1 greater other, program should take 1 fork. if opposite true, should take path. , should same thing, if value being compared nudged in direction should still make compare true.
it's difficult question phrase, wrote demonstrate -
float = random(); float b = random(); // returns number (no infinity or nans) if(a < b){ if( !(a < b + float_episilon) ) launchthemissiles(); buildhospitals(); }else if(a >= b){ if( !(a >= b - float_episilon) ) launchthemissiles(); buildorphanages(); }else{ launchthemissiles(); // should never called, in branch }
given code, launchthemissiles()
guaranteed never called?
if can guarantee a
, b
not nans or infinities, can do:
if (a<b) { … } else { … }
the set of floating point values except infinities , nans comprise total ordering (with glitch 2 representations of zero, shouldn't matter you), not unlike working normal set of integers — difference magnitude of intervals between subsequent values not constant, integers.
in fact, ieee 754 has been designed comparisons of non-nan non-infinity values of same sign can done same operations normal integers (again, glitch zero). so, in specific case, can think of these numbers of “better integers”.
Comments
Post a Comment