What is math.cos() in Scala?

The cos() function in Scala returns the cosine of a number. To be more specific, it returns the cosine of a number in radians.

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

Figure 1: Mathematical representation of cosine function

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


This cos() function only works for right-angled triangles.

Syntax


Double cos(Double number)

Parameter

This function requires a number that represents an angle in radians as a parameter.

To convert degrees to radians, use the formula below.


radians = degrees * ( Pi / 180.0 )

Return value

cos() returns the cosine of a number in radians that is sent as a parameter.


If the parameter value is NaNNot a Number or positive infinity or negative infinity, it returns NaN.

Code

import scala.math._
object Main extends App {
//positive number in radians
println(s"The value of cos(2.3) = ${cos(2.3)}");
// negative number in radians
println(s"The value of cos(-2.3) = ${cos(-2.3)}");
//converting the degrees angle into radians and then applying cos()
// degrees = 45
// PI = 3.14159265
// result first converts degrees to radians then apply cos
println(s"The value of cos(45) = ${cos(45 * (Pi / 180))}");
//error outputs
println(s"The value of cos(Double.PositiveInfinity) = ${cos(Double.PositiveInfinity)}");
println(s"The value of cos(Double.NegativeInfinity) = ${cos(Double.NegativeInfinity)}");
println(s"The value of cos(Double.NaN) = ${cos(Double.NaN)}");
}

Free Resources