20

Given an arbitrary finite floating point number, is there a way to determine what the next representable floating point number? For example, given 1.0f, by definition the next largest representable number is 1.0f + std::numeric_limits<float>::epsilon(). Is there a way to synthesize an epsilon for any value - not just 1.0f - without resorting to bit twiddling and/or explicit knowledge of how the machine represents floating point values?

tgoodhart
  • 3,111
  • 26
  • 37
  • I don't think it can be done without bit twiddling and explicit knowledge of the machine representation, but I'm not super-familiar with std::numeric_limits stuff – Mooing Duck Sep 13 '11 at 21:06

2 Answers2

22

In C++11, you use std::nextafter(). Lacking that, on a C99 system, you use nextafterf, nextafter, or nextafterl from the C math library (for types float, double, and long double, respectively).

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Stephen Canon
  • 103,815
  • 19
  • 183
  • 269
3
int exponent;
significand= frexp(number, &exponent);
significand+= epsilon;
next= ldexp(significand, exponent);

What this does is extract the mantissa, increment it by the floating point epsilon, then rebuild the floating point number. That should be the next representable number you would get by fiddling with the bits of the mantissa (and exponent on mantissa overflow).

MSN
  • 53,214
  • 7
  • 75
  • 105
  • I upvoted, because it is useful to me, but I don't think this is valid for the entire range. In testing my implementation I tried moving away from zero and then back to it, but I couldn't get to zero. – cgmb Jun 06 '12 at 20:49
  • I don't believe this handles denormalized values correctly, or if the significand overflows, in which case the exponent needs to be incremented. – Fooberman Dec 21 '13 at 19:29