Compute the next representable double-precision floating-point number
#include <math.h>
double nextafter ( double x,
double y);
float nextafterf ( float x,
float y );
long double nextafterl ( long double x,
long double y);
The nextafter(), nextafterf(), and nextafterl() functions compute the next representable double-precision floating-point value following x in the direction of y.
To check for error situations, use feclearexcept() and fetestexcept(). For example:
The next machine floating-point number of x in the direction towards y.
| If | These functions return: | Errors: |
|---|---|---|
| x equals y | y | — |
| x is finite, and the correct value would overflow | Inf | FE_OVERFLOW |
| x or y is NaN | NaN | — |
| x != y, and the correct value is subnormal, zero, or underflows | The correct value (if representable), or 0.0 | FE_UNDERFLOW |
These functions raise FE_INEXACT if the FPU reports that the result can't be exactly represented as a floating-point number.
#include <stdio.h>
#include <inttypes.h>
#include <math.h>
#include <fenv.h>
#include <stdlib.h>
void dump_to_hex(double d) {
printf("0x%08x %08x \n",
(uint32_t)(*((uint64_t*)&d) >> 32),
(uint32_t)(*((uint64_t*)&d)));
}
int main(int argc, char** argv)
{
double a, b, c;
int except_flags;
a = 0;
feclearexcept(FE_ALL_EXCEPT);
b = nextafter(a, -1);
except_flags = fetestexcept(FE_ALL_EXCEPT);
if(except_flags) {
/* An error occurred; handle it appropriately. */
}
feclearexcept(FE_ALL_EXCEPT);
c = nextafter(a, 1);
except_flags = fetestexcept(FE_ALL_EXCEPT);
if(except_flags) {
/* An error occurred; handle it appropriately. */
}
printf("Next possible value before %f is %f \n", a, b);
printf("-->"); dump_to_hex(a);
printf("-->"); dump_to_hex(b);
printf("Next possible value after %f is %f \n", a, c);
printf("-->"); dump_to_hex(a);
printf("-->"); dump_to_hex(c);
return EXIT_SUCCESS;
}
produces the output:
Next possible value before 0.000000 is 0.000000 -->0x00000000 00000000 -->0x80000000 00000001 Next possible value after 0.000000 is 0.000000 -->0x00000000 00000000
| Safety: | |
|---|---|
| Cancellation point | No |
| Interrupt handler | No |
| Signal handler | No |
| Thread | Yes |