Java Math.ulp
Return the spacing associated with one unit in the last place of a floating-point value.
A simple example
Math.ulp
- Start with 1.0
- Do this Measure one unit in the last place
- Result 2⁻⁵²
Syntax
Math.ulp(reading)
JDK 21 method signatures (2)
public static double ulp(double d)
public static float ulp(float f)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaInspect the resolution of a sensor calculation
A sensor stores readings in a binary floating-point format with limited precision. Inspect or adjust the scale of the sample value so the calibration code can account for representable steps.
class Main {
public static void main(String[] args) throws Exception {
double reading = 1.0;
System.out.println(Math.ulp(reading));
}
}
2.220446049250313E-16
At one, the next larger double is approximately 2.22 times ten to the minus sixteen away.
Inspect the scale near two units
A calibration test stores a double reading of 2.0. The developer measures the gap from that value to its next larger representable reading.
Using 2 gives 4.440892098500626e-16 for this measurement.
Check precision in a high range
A measurement program switches its reference level to 1024.0. The tester records how far apart neighbouring double readings are at that level.
Using 1024 gives 2.2737367544323206e-13 for this measurement.
What to watch for
The spacing changes with magnitude. It measures representation precision rather than physical sensor accuracy.