nextafter() and nexttoward() in C/C++

The nextafter() and nexttoward() functions in C are used to find the next representable floating-point value after a given number in a specified direction. These functions are part of the math.h library and are useful for precise floating-point arithmetic operations.

Syntax

double nextafter(double x, double y);
float nextafterf(float x, float y);
long double nextafterl(long double x, long double y);

double nexttoward(double x, long double y);
float nexttowardf(float x, long double y);
long double nexttowardl(long double x, long double y);

Parameters

  • x − The starting value
  • y − The direction value. The function returns the next representable value after x in the direction of y

Return Value

Both functions return the next representable floating-point value after x in the direction of y. The key difference is that nexttoward() uses a long double parameter for the direction, providing higher precision.

Example

#include <stdio.h>
#include <math.h>

int main() {
    /* The nextafter function */
    printf("Smallest representable number after 0 towards 1: %e\n", nextafter(0.0, 1.0));
    printf("Largest representable number before 0 towards -1: %e\n", nextafter(0.0, -1.0));
    printf("Next representable number after 0.8 towards 0: %e\n", nextafter(0.8, 0.0));
    
    printf("\n");
    
    /* using nexttoward */
    printf("Smallest representable number after 0 towards 1: %e\n", nexttoward(0.0, 1.0L));
    printf("Largest representable number before 0 towards -1: %e\n", nexttoward(0.0, -1.0L));
    printf("Next representable number after 0.8 towards 0: %e\n", nexttoward(0.8, 0.0L));
    
    return 0;
}
Smallest representable number after 0 towards 1: 4.940656e-324
Largest representable number before 0 towards -1: -4.940656e-324
Next representable number after 0.8 towards 0: 7.999999e-001

Smallest representable number after 0 towards 1: 4.940656e-324
Largest representable number before 0 towards -1: -4.940656e-324
Next representable number after 0.8 towards 0: 7.999999e-001

Key Points

  • The smallest representable positive double value is approximately 4.940656e-324
  • nextafter() uses the same type for both parameters
  • nexttoward() uses long double for the direction parameter, offering higher precision
  • These functions are essential for implementing precise numerical algorithms

Conclusion

The nextafter() and nexttoward() functions provide precise control over floating-point value progression. They are particularly useful in numerical computing where exact representation boundaries matter.

Updated on: 2026-03-15T10:38:02+05:30

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements