What is the closest double to 1.0, i.e. 1.0?

Is there a way to programmatically get a double that is closest to 1.0, but not really 1.0?

One hacked way to do this is a memcpy double with an integer of the same size, and then subtract it. The way the IEEE754 floating point formats work will lead to a decrease in the exponent by one when the fractional part changes from all zeros (1.000000000000) to all (1.111111111111). However, there are machines where integers are stored low-endian, while floating-point is stored big-endian, so this will not always work.

+79
c ++ floating-point floating-accuracy
Aug 6 '16 at 7:52
source share
4 answers

In C and C ++, the following gives the closest 1.0 value:

#include <limits.h> double closest_to_1 = 1.0 - DBL_EPSILON/FLT_RADIX; 

Note, however, that in later versions of C ++, limits.h deprecated in favor of climits . But then if you use C ++ 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, with 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 versions of C ++) include cmath and use std::nextafter .

+20
Aug 6 '16 at 16:02
source share

With C ++ 11, you can use nextafter to get the following representable value in a given direction:

 std::nextafter(1., 0.); // 0.99999999999999989 std::nextafter(1., 2.); // 1.0000000000000002 

Demo version

+128
Aug 6 '16 at 7:59
source share

In C, you can use this:

 #include <float.h> ... double value = 1.0+DBL_EPSILON; 

DBL_EPSILON is the difference between 1 and the smallest value greater than 1 that appears.

You need to print it up to a few digits to see the actual value.

On my platform, printf("%.16lf",1.0+DBL_EPSILON) is given 1.0000000000000002 .

+24
Aug 06 '16 at 8:01
source share

In C ++, you can also use this

 1 + std::numeric_limits<double>::epsilon() 
+3
Aug 6 '16 at 8:17
source share



All Articles