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