I would use the punning type:
double epsFor( double x ) { union { double d; unsigned long long i; } tmp; tmp.d = x; ++ tmp.i; double results = tmp.d - x; return results; }
(Formally, this behavior is undefined, but in practice I donβt know about the modern compiler, where it will fail.)
EDIT:
Note that C ++ allows excessive precision in an intermediate expression; since we are dealing with exact results here, the originally published function may produce incorrect results if you used it directly in the expression, rather than assigning it a double . I added an assignment to the function to avoid this, but keep in mind that many compilers are not standard in this regard, at least by default. (g ++ is a good example of where you need a special version of compatible behavior, at least when optimization is turned on. If you use g ++, you must specify -ffloat-store if you want to get the correct results.)
James kanze
source share