*Compute the next representable floating-point number*

#include <math.h> double nexttoward ( doublex, long doubley); float nexttowardf ( floatx, long doubley); long double nexttowardl ( long doublex, long doubley);

`x`- The number that you want the next number after.
`y`- A number that specifies the direction you want to go; see below.

The nexttoward(), nexttowardf(), and nexttowardl() 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():

- Call
`feclearexcept(FE_ALL_EXCEPT)`before calling nexttoward(), nexttowardf(), or nexttowardl(). - On return, if
`fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW)`is nonzero, then an error has occurred.

The next machine floating-point number of `x` in the
direction towards `y`, converted to the type that the function returns.

- If
`x`equals`y`,`y`(of the appropriate type) is returned. - If
`x`is finite, and the correct function value would overflow, a range error occurs, and the functions return ±HUGE_VAL, ±HUGE_VALF, or ±HUGE_VALL (with the same sign as`x`), depending on the function. - If
`x`or`y`is NaN, NaN is returned. - If
`x`!=`y`, and the correct function value is subnormal, zero, or underflows, a range error occurs, and the correct function value (if representable) or 0.0 is returned.

- FE_OVERFLOW
- The result would cause an overflow.
- FE_UNDERFLOW
- The value of
`x`isn't equal to`y`, and the correct function value is subnormal, zero, or underflows.

#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 = nexttoward(a, -1); except_flags = fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW); if(except_flags) { /* An error occurred; handle it appropriately. */ } feclearexcept(FE_ALL_EXCEPT); c = nexttoward(a, 1); except_flags = fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW); 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 |