开发者

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

开发者 https://www.devze.com 2023-04-04 20:54 出处:网络
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 nu

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 twiddlin开发者_如何学JAVAg and/or explicit knowledge of how the machine represents floating point values?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号