What is Math.ulp() in Java?

ulp() is a static method of the Math class in Java that returns the provided argument’s ulp.

A ulp (unit in the last place) of a double value is the positive distance between the floating-point value of the argument and the next larger double value in magnitude.

  • The argument’s ulp is independent of the argument’s sign i.e., ulp(-x) = ulp(x).

  • The result is NaN if the argument is NaN.

  • If the argument is positive or negative infinity, the result is positiveinfinity.

  • If the argument is positive or negative zero, the result is Double.MIN_VALUE.

  • The result is equal to (22^971971) if the argument is ±Double.MAX_VALUE.

The ulp() method is defined in the Math class, which is defined in the java.lang package.

To import the Math class, use the following import statement.

import java.lang.Math;

Method signature

The ulp() method’s signature is as follows.

public static double ulp(double d)

Parameters

  • double d: The floating-point value.

Return value

This method returns the size of the argument’s ulp.

Overloaded methods

The ulp() method can be overloaded by providing a float value as an argument:

  • public static float ulp(float f)

Code

The code below shows how the ulp() method works in Java.

import java.lang.Math;
public class Main{
public static void main(String[] args){
double d = 23;
double result = Math.ulp(d);
System.out.println("ulp(" + d + ") = "+ result);
d = -1232.233454;
result = Math.ulp(d);
System.out.println("ulp(" + d + ") = "+ result);
}
}

For each of the double values provided, the ulp() method returns their corresponding ulp printed accordingly.

Free Resources