What is Math.acos() in Scala?

The acos() function, also called the arc cosine function, returns the inverse cosine of a number. To be more specific, it returns the inverse cosine of a number in radians.

The image below shows the mathematical representation of the acos() function.

Mathematical representation of inverse cosine function

The scala.math._ header file is required for this function.

To convert degrees to radians, use the formula below:

radians = degrees * ( Pi / 180 )

Syntax

Double acos(Double number)

Parameters

This function requires a number as a parameter. The parameter must be a double value between -1 and 1.

  • -1 <= parameter <= 1

Return value

acos() returns the inverse cosine of the number (in radians) that is sent as a parameter. The return value lies in the interval [0, pi] radians.

If the parameter value is an error value, i.e., greater than one or less than one or infinity or NaN, then acos() returns NaN.

Example

import scala.math._
object Main extends App {
//positive number in radians
println(s"The value of acos(0.5) = ${acos(0.5)} Radians");
// negative number in radians
println(s"The value of acos(-0.5) = ${acos(-0.5)} Radians");
//applying acos() and then converting the result in radians to degrees
// radians = 0.5
// PI = 3.14159265
println(s"The value of acos(0.5) = ${acos(0.5) * (180 / Pi)} Degrees");
//error outputs
println(s"The value of acos(Double.PositiveInfinity) = ${acos(Double.PositiveInfinity)}");
println(s"The value of acos(Double.NegativeInfinity) = ${acos(Double.NegativeInfinity)}");
println(s"The value of acos(Double.NaN) = ${acos(Double.NaN)}");
println(s"The value of acos(2) = ${acos(2)}");
println(s"The value of acos(-2) = ${acos(-2)}");
}

Free Resources