Library contents

Java Math.nextAfter

Move one representable floating-point value in the direction of a target.

A simple example

Math.nextAfter

  1. Start with 1.0
  2. Do this Take one double-precision step upward
  3. Result 1.0000000000000002
The result is the closest representable double above 1.0.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.nextAfter(1.0, 2.0));
    }
}
Output
1.0000000000000002

Syntax

Java syntax
Math.nextAfter(reading, target)
JDK 21 method signatures (2)
public static double nextAfter(double start, double direction)
public static float nextAfter(float start, double direction)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Step toward a calibration target

A calibration routine needs to test the nearest representable value on one side of a limit. Move by one floating-point step so the boundary test uses a value the computer can actually store.

From the programdouble reading = 1.0
Result1.0000000000000002
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        double reading = 1.0;
        double target = 2.0;
        System.out.println(Math.nextAfter(reading, target));
    }
}
Output
1.0000000000000002

Starting at one and aiming for two advances only to the next double above one.

Advertisements

Probe a lamp setting from below

The lamp controller starts at two units. A test requests one floating-point step in the direction of three to check the upper neighbour.

Given2 · 3
Worked result2.0000000000000004

Using 2 · 3 gives 2.0000000000000004 for this measurement.

Probe a limit from above

A meter reads eight units before calibration. The software takes one representable step toward zero to exercise the lower side of the limit.

Given8 · 0
Worked result7.999999999999999

Using 8 · 0 gives 7.999999999999999 for this measurement.

What to watch for

The target selects the direction. This method never jumps the full distance unless the values are adjacent or equal.

Documentation for Math.nextAfter