Scala Tutorial Scala References

Scala - Math nextAfter() Method



The Scala Math nextAfter() method returns the floating-point number adjacent to the first argument in the direction of the second argument. If both arguments compare as equal a value equivalent to the second argument is returned. In special cases it returns the following:

  • If either argument is a NaN, then NaN is returned.
  • If both arguments are signed zeros, a value equivalent to direction is returned.
  • If start is infinite and direction has a value such that the result should have a smaller magnitude, Double.MaxValue or Float.MaxValue with the same sign as start is returned.
  • If start is ±Double.MinValue or ±Float.MinValue and direction has a value such that the result should have a smaller magnitude, then a zero with the same sign as start is returned.
  • If start is equal to ±Double.MaxValue or ±Float.MaxValue and direction has a value such that the result should have a larger magnitude, an infinity with same sign as start is returned.

Syntax

  def nextAfter(start: Double, direction: Double): Double = 
                     java.lang.Math.nextAfter(start, direction)
  def nextAfter(start: Float, direction: Double): Float = 
                     java.lang.Math.nextAfter(start, direction)

Parameters

start Specify starting floating-point value.
direction Specify value for direction.

Return Value

Returns the floating-point number adjacent to the first argument in the direction of the second argument.

Exception

NA.

Example:

In the example below, Math.nextAfter() method returns the floating-point number adjacent to the first argument in the direction of the second argument.

object MainObject {
  def main(args: Array[String]) {
    println("Math.nextAfter(10.55, 0) = "
            + Math.nextAfter(10.55, 0)); 
    println("Math.nextAfter(-10.55, 0) = "
            + Math.nextAfter(-10.55, 0)); 
    println("Math.nextAfter(0, -10) = "
            + Math.nextAfter(0, -10));     
    println("Math.nextAfter(Double.NaN, 0) = "
            + Math.nextAfter(Double.NaN, 0));             
    println("Math.nextAfter(Double.PositiveInfinity, 0) = "
            + Math.nextAfter(Double.PositiveInfinity, 0));  
  }
}

The output of the above code will be:

Math.nextAfter(10.55, 0) = 10.549999999999999
Math.nextAfter(-10.55, 0) = -10.549999999999999
Math.nextAfter(0, -10) = -1.4E-45
Math.nextAfter(Double.NaN, 0) = NaN
Math.nextAfter(Double.PositiveInfinity, 0) = 1.7976931348623157E308

❮ Scala - Math Methods