I'd use type punning:
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 is undefined behavior, but in practice, I don't
know of a modern compiler where it will fail.)
EDIT:
Note that C++ allows excessive precision in intermediate
expressions; since we're concerned here with exact results, the
originally posted function could give wrong results if you used
it directly in an expression, rather than assigning it to
a double
. I've added an assignment in the function to avoid
this, but be aware that a lot of compilers are not standard
conform in this regard, at least by default. (g++ is a good
example of one where you need a special option to have
conformant behavior, at least when optimization is turned on.
If you're using g++, you must specify the
-ffloat-store
option if you want correct results.)