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:

  1. If x=yx=y, then the nexttowardf() function returns yy.
  2. If either x or y are Not a Number (NaN), then the function returns NaN.
  3. 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:

  1. In the case of an overflow, the HUGE_VALF macro is returned.
  2. If the return value is infinity despite a finite x value, the FE_INEXACT and FE_OVERFLOW errors are returned due to overflow.
  3. If the result is not normal or zero, this indicates an underflow. In this case, the FE_INEXACT and FE_UNDERFLOW flags are raised.

Example

Below is an example of how you can use the nexttowardf() function. It calculates the next floating-point number after 00 in the direction of 11 (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

Copyright ©2025 Educative, Inc. All rights reserved