What's the closest double to 1.0, that isn't 1.0?
Since C++11, you may use nextafter
to get next representable value in given direction:
std::nextafter(1., 0.); // 0.99999999999999989
std::nextafter(1., 2.); // 1.0000000000000002
Demo
In C and C++, the following gives the closest value to 1.0:
#include <limits.h>
double closest_to_1 = 1.0 - DBL_EPSILON/FLT_RADIX;
Note however that in later versions of C++, limits.h
is deprecated in favour of climits
. But then, if you are using C++ specific code anyway, you can use
#include <limits>
typedef std::numeric_limits<double> lim_dbl;
double closest_to_1 = 1.0 - lim_dbl::epsilon()/lim_dbl::radix;
And as Jarod42 writes in his answer, since C99 or C++11 you can also use nextafter
:
#include <math.h>
double closest_to_1 = nextafter(1.0, 0.0);
Of course in C++ you can (and for later C++ versions should) include cmath
and use std::nextafter
instead.