What is Math.log() in Scala?

The log() function in Scala calculates the natural logarithm of a number.

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

Mathematical representation of the log() function

The log() function requires the following module:

import scala.math._

Syntax

Double log(Double number)

Parameters

This function requires:

  • A numbermust be greater than 0 for which the logarithm is to be calculated.

Return value

log() returns the natural logarithm of the number sent as a parameter.

  • If the parameter value is positive infinity, then log() returns positive infinity.
  • If the parameter value is NaN, less than zero, or negative infinity, then log() returns NaN.
  • If the parameter value is zero, then log() returns negative infinity.

Code

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

Free Resources