Generate next largest or smallest representable floating point number without bit twiddling

后端 未结 2 1994
执笔经年
执笔经年 2020-12-09 17:01

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 ne

相关标签:
2条回答
  • 2020-12-09 17:20

    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).

    0 讨论(0)
  • 2020-12-09 17:28
    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).

    0 讨论(0)
提交回复
热议问题