How to loop over exact representations of floating point numbers?

I am trying to accurately execute a loop from one floating point number to the next. Let's say I need to loop from std::numeric_limits<float>::epsilon()to 1, which are the accurately represented IEEE754 numbers. My code is:

 using nld = std::numeric_limits<float>;
 auto h = nld::epsilon();
 for (; h < 1; h = std::nextafter(h, 1)) {
     std::cerr << "h: " << h << std::endl;
 }

which loops infinitely beacuse h represent exactly, therefore nextaftercontinues to return it. I also know that adding machine epsilon to h in a loop will not reduce it: floating-point numbers are not evenly distributed. How do I loop over the exact representations of IEEE754 numbers?

The problem not equally spacedis presented here:

 using nld = std::numeric_limits<float>;
 auto h = nld::epsilon();
 for (; h < 4; h += nld::epsilon()) {
     if (h = h + nld::epsilon()) {
         std::cerr << "h: " << h << std::endl;
     }
 }

which keeps printing 2for me

+4
2

:

nextafter - , . , .

cppreference std::nextafter:

float nextafter( float from, float to ); (1) ( ++ 11)
double nextafter( double from, double to ); (2) ( ++ 11)
long double nextafter( long double from, long double to ); (3) ( ++ 11)
Promoted nextafter( Arithmetic from, Arithmetic to ); (4) ( ++ 11)

...

4) , (1-3). - , double. long double, Promoted long double, double.

to 1, int, 4 double. , float f, (float)nextafter((double)f, 1) f: , double float, float .

, float, - , to float. , 1.0f 1.

+2

, notmal , , .

: :

float nextfloat(float in)
{   
   union { float f; uint32_t i; } a;
   a.f=in;
   a.i++;
   return(a.f);
}

, , float uint32_t, double uint64_t... undefined, , , poart .

0

All Articles