What is nexttowardf in C?
Overview
The nexttowardf() calculates the next value after a number x in the direction of another number y in a precise manner. nexttowardf() is similar to the nextafter() function.
nexttowardf() is defined in the <math.h> library, so you must include the <math.h> library at the beginning of your program as shown below:
#include<math.h>
The nexttowardf() function is defined in the <math.h> header files as shown below:
float nexttowardf( float x, long double y );
Parameters
The nexttowardf() function takes two parameters, x and y, of type float and long double respectively.
Return value
x is defined as ‘from’ and y as ‘to’ because the function returns the next floating-point number from x and in the direction of y.
Moreover, the return values vary for some distinct values of x and y:
- If , then the
nexttowardf()function returns . - If either
xoryareNot a Number (NaN), then the function returnsNaN. - If the resultant floating point underflows, the return value would still be correct.
The return value never depends on the current rounding mode in any case.
Error handling
The following errors can be returned if the nexttowardf() function is not executed successfully:
- In the case of an overflow, the
HUGE_VALFmacro is returned. - If the return value is infinity despite a finite
xvalue, theFE_INEXACTandFE_OVERFLOWerrors are returned due to overflow. - If the result is not normal or zero, this indicates an underflow. In this case, the
FE_INEXACTandFE_UNDERFLOWflags are raised.
Example
Below is an example of how you can use the nexttowardf() function. It calculates the next floating-point number after in the direction of (positive numbers).
#include<stdio.h>#include<math.h>int main() {float from = 0;long double to = 1;float result = nexttowardf(from, to);printf("the next number from 0 in the direction of 1 is: %f\n", result);return 0;}
Free Resources