In C, nextafter() returns the next representable double after x in the direction of y. Floating-point numbers have gaps. This function takes one tiny step toward y.
You pass two double values: the start point and the direction target. Include <math.h>. On GCC, link with -lm. Related helpers include nextup() and nextdown().
If x already equals y, nextafter returns y. Otherwise it moves by one unit in the last place (one ULP) toward y.
Syntax
Pass the current value and the direction value.
C
nextafter(1.0, 2.0);
Call
What it does
nextafter(1.0, 2.0)
Returns the smallest double greater than 1.0.
Include <math.h>. On GCC, link with -lm. Both arguments are required.
Library declarations
C
double nextafter(double x, double y);
float nextafterf(float x, float y);
long double nextafterl(long double x, long double y);
Parameters
Parameter
Description
x
Required. The starting double.
y
Required. The direction target. The result steps from x toward y.
Return Value
Return Value
Description
double
The next representable value after x toward y, or y if x equals y.
C Examples
Example 1 — Step Up from 1.0
Move one representable step above 1.0 and print the difference.
C
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 1.0;
double n = nextafter(x, 2.0);
printf("next = %.17f\n", n);
printf("diff = %.17e\n", n - x);
return 0;
}
Output
next = 1.0000000000000002
diff = 2.2204460492503131e-16
How It Works
Start at 1.0. A common reference point.
Aim toward 2.0. That chooses the upward direction.
One ULP up. The next double after 1.0 appears.
Diff is epsilon-ish. Around 1.0 this gap is about 2.22e-16.
Example 2 — Step Toward Zero
Move one step downward from a value by aiming at a smaller target.
C
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 10.0;
double n = nextafter(x, 0.0);
printf("%.17f\n", n);
return 0;
}
Output
9.9999999999999982
How It Works
Start at 10. A larger magnitude than 1.
Aim at 0. Direction is downward.
One step lower. The printed value is just under 10.
Spacing grows. ULP size depends on the magnitude.
Example 3 — Walk a Few Steps
Call nextafter in a short loop to climb several representable values.
C
#include <stdio.h>
#include <math.h>
int main(void) {
double x = 0.0;
int i;
for (i = 0; i < 3; i++) {
x = nextafter(x, 1.0);
printf("%.17e\n", x);
}
return 0;
}