Scala Tutorial Scala References

Scala - Math sqrt() Method



The Scala Math sqrt() method returns the square root of the given number. In special cases it returns the following:

  • If the argument is NaN or less than zero, then the result is NaN.
  • If the argument is positive infinity, then the result is positive infinity.
  • If the argument is positive zero, then the result is the same as the argument.

Syntax

def sqrt(x: Double): Double = java.lang.Math.sqrt(x)

Parameters

x Specify a number.

Return Value

Returns the square root of the specified number.

Exception

NA.

Example:

In the example below, sqrt() method is used to find out the square root of the given number.

import scala.math._

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

The output of the above code will be:

sqrt(10) = 3.1622776601683795
sqrt(100) = 10.0
sqrt(50) = 7.0710678118654755
sqrt(0) = 0.0
sqrt(-50) = NaN
sqrt(Double.NaN) = NaN
sqrt(Double.PositiveInfinity) = Infinity
sqrt(Double.NegativeInfinity) = NaN

❮ Scala - Math Methods

5