What is Math.sqrt() in Scala?

The sqrt() function returns the square root of a number sent as a parameter.

Figure 1 below shows the mathematical representation of the sqrt() function.

Figure 1: Mathematical representation of the sqrt() function

The following module is required for this function:

import scala.math._

Syntax

Double sqrt(Double number)

Parameter

This function requires a number as a parameter.

Return value

  • If the input is a valid positive double number, then the square root of the number sent as a parameter is returned.
  • If the parameter value is positive infinity, then it returns positive infinity.
  • If the parameter value is NaN, less than zero, or negative infinity, then it returns NaN.

Example

import scala.math._
object Main extends App {
//positive number
println(s"The value of sqrt(10) = ${sqrt(10)}");
println(s"The value of sqrt(0) = ${sqrt(0)}");
println(s"The value of sqrt(4) = ${sqrt(4)}");
//error outputs
println(s"The value of sqrt(Double.PositiveInfinity) = ${sqrt(Double.PositiveInfinity)}");
println(s"The value of sqrt(Double.NegativeInfinity) = ${sqrt(Double.NegativeInfinity)}");
println(s"The value of sqrt(Double.NaN) = ${sqrt(Double.NaN)}");
println(s"The value of sqrt(-1) = ${sqrt(-1)}");
}

Free Resources