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 adouble valueis the positive distance between the floating-point value of the argument and the next largerdoublevalue in magnitude.
-
The argument’s
ulpis independent of the argument’s sign i.e.,ulp(-x) = ulp(x). -
The result is
NaNif the argument isNaN. -
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 (^) if the argument is
±Double.MAX_VALUE.
The
ulp()method is defined in theMathclass, which is defined in thejava.langpackage.
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.