What is Math.hypot() in Scala?

The hypot() function in Scala returns the length of the hypotenuse of a right-angle triangle.

The mathematical formula to calculate the hypotenuse is as follows.

hypotenuse = sqrt(length^2 + base^2)

The illustration below shows the visual representation of the hypot() function.

Visual representation of the hypot() function

The following module is required for this function:

import scala.math._

Syntax

Double hypot(Double length, Double base)

Parameters

The hypot() function requires length and base as parameters.

Return value

hypot() returns the length of the hypotenuse of the right-angle triangle based on its length and base, which are sent as parameters.

  • If the parameter value of length, base, or both is PositiveInfinity, then hypot() returns PositiveInfinity.
  • If the parameter value of length, base, or both is NegativeInfinity, then hypot() returns zero.
  • If the parameter value of length, base, or both is NaN, then hypot() returns NaN.

Code

import scala.math._
object Main extends App {
//length=10 and base=10
println(s"The value of hypot(10, 10) = ${hypot(10, 10)}");
//length=4 and base=6
println(s"The value of hypot(4, 6) = ${hypot(4, 6)}");
//error ouput
println(s"The value of hypot(Double.PositiveInfinity,Double.PositiveInfinity) = ${hypot(Double.PositiveInfinity,Double.PositiveInfinity)}");
println(s"The value of hypot(Double.NegativeInfinity,Double.NegativeInfinity) = ${hypot(Double.NegativeInfinity,Double.NegativeInfinity)}");
println(s"The value of hypot(Double.NaN,Double.NaN) = ${hypot(Double.NaN,Double.NaN)}");
}

Free Resources