Scala Tutorial Scala References

Scala - Math ulp() Method

The Scala Math ulp() method returns the size of the unit of least precision (ulp) of the argument. An ulp is the positive distance between the given Double/Float value and the Double/Float value next larger in magnitude. In special cases it returns the following:

  • If the argument is NaN, then the result is NaN.
  • If the argument is positive or negative infinity, then the result is positive infinity.
  • If the argument is zero, then the result is Double.MinValue or Float.MinValue.


def ulp(x: Double): Double = java.lang.Math.ulp(x)
def ulp(x: Float): Float = java.lang.Math.ulp(x)


x Specify a floating-point value whose ulp need to be returned.

Return Value

Returns the size of an ulp of the argument.




In the example below, ulp() method returns the size of an ulp of the argument.

import scala.math._

object MainObject {
  def main(args: Array[String]) {
    println(s"ulp(10) = ${ulp(10)}");  
    println(s"ulp(100) = ${ulp(100)}"); 
    println(s"ulp(50) = ${ulp(50)}"); 
    println(s"ulp(0) = ${ulp(0)}");
    println(s"ulp(Double.NaN) = ${ulp(Double.NaN)}"); 
    println("ulp(Double.PositiveInfinity) = "
            + ulp(Double.PositiveInfinity));

The output of the above code will be:

ulp(10) = 9.536743E-7
ulp(100) = 7.6293945E-6
ulp(50) = 3.8146973E-6
ulp(0) = 1.4E-45
ulp(Double.NaN) = NaN
ulp(Double.PositiveInfinity) = Infinity

❮ Scala - Math Methods