In C, the nextafter() is a standard library function that is used to find the next representable floating-point value after a given number in the direction of another specified number.
In this article, we will learn how to use the nextafter() function in C and its variant for different floating point types.
Syntax of nextafter() in C
double nextafter(double x, double y);Parameters
The nextafter() function in C takes two parameters:
- x: The starting point (a floating-point number).
- y: The direction point (a floating-point number).
Return Value
- The return value is the next representable floating-point value after x in the direction of y.
- If x equals y, the function returns y.
Variants of nextafter in C
The nextafter() function comes in three variations, catering to different floating-point types:
nextafterf() for float
float nextafterf(float x, float y);nextafterl() for long double
long double nextafterl(long double x, long double y);Examples of nextafter() in C
Example 1: Program to demonstrate how to use the nextafter() function
// C Program to demonstrate the nextafter() function
#include <math.h>
#include <stdio.h>
int main()
{
double x = 1.0, y = 2.0;
double result = nextafter(x, y);
// Print the result
printf("The next representable value after %.2lf "
"towards %.2lf is: %.17g\n",
x, y, result);
return 0;
}
Output
The next representable value after 1.00 towards 2.00 is: 1.0000000000000002
Time Complexity: O(1)
Auxiliary Space: O(1)
Example 2: Program to demonstrate the use of the variants of the nextafter() function
// C program to demonstrate the nextafter() function for
// different data types
#include <math.h>
#include <stdio.h>
int main()
{
double x1 = 1.0, y1 = 2.0;
float x2 = 2.0f, y2 = 4.0f;
long double x3 = 3.0l, y3 = 5.0l;
// nextafter function for double
double result1 = nextafter(x1, y1);
// nextafterf function for float
float result2 = nextafterf(x2, y2);
// nextafterl function for long double
long double result3 = nextafterl(x3, y3);
// Print the results
printf("The next representable value after %.2lf "
"towards %.2lf is: %.17g\n",
x1, y1, result1);
printf("The next representable value after %.2f "
"towards %.2f is: %.8g\n",
x2, y2, result2);
printf("The next representable value after %.2Lf "
"towards %.2Lf is: %.21Lg\n",
x3, y3, result3);
return 0;
}
Output
The next representable value after 1.00 towards 2.00 is: 1.0000000000000002
The next representable value after 2.00 towards 4.00 is: 2.0000002
The next representable value after 3.00 towards 5.00 is: 3.00000000000000000022
Time Complexity: O(1)
Auxiliary Space: O(1)