Java .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
numisNaN,NaNwill be returned. - If
numis positive or negative zero, then the return value will beDouble.MIN_VALUEorFloat.MIN_VALUEwhich is the lowest number afloatordoublecan represent. - If
numis positive or negative infinity, then the return value will be positive infinity. - If
numis a number, thennumwill have the same return value as-num. - If
numisDouble.MAX_VALUEorFloat.MAX_VALUE, then the return value will be 2971 fordoubleand 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
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours