.ulp()
Published Dec 18, 2022Updated May 15, 2024
Contribute to Docs
The Math.ulp()
method returns the unit of least precision of a given number. It calculates the distance between the given float
or double
value and the next largest float
or double
value in magnitude.
Syntax
Math.ulp(num);
The num
parameter can be of type float
or double
and the return value will be of the same type.
Special cases include the following:
- If
num
isNaN
,NaN
will be returned. - If
num
is positive or negative zero, then the return value will beDouble.MIN_VALUE
orFloat.MIN_VALUE
which is the lowest number afloat
ordouble
can represent. - If
num
is positive or negative infinity, then the return value will be positive infinity. - If
num
is a number, thennum
will have the same return value as-num
. - If
num
isDouble.MAX_VALUE
orFloat.MAX_VALUE
, then the return value will be 2971 fordouble
and 2104 forfloat
.
Example 1
// Test.javaimport java.lang.Math;public class Test {public static void main(String args[]) {double num = 23.44;System.out.println(Math.ulp(num));}}
This will output:
3.552713678800501E-15
Example 2
import java.lang.Math;public class Test {public static void main(String args[]) {double num = 23.44;System.out.println(Math.ulp(num) + " = " + Math.ulp(-num));System.out.println(Math.ulp(0/0.));System.out.println(Math.ulp(0.));System.out.println(Math.ulp(1./0));}}
This will output:
3.552713678800501E-15 = 3.552713678800501E-15NaN4.9E-324Infinity
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly17 hours