What is Math.log() in Ruby?

The log() function in Ruby calculates the logarithm of a number to the base, or calculates the natural logarithm of a number if the user does not specify the base.

Figure 1 shows the mathematical representation of the log() function.

Figure 1: Mathematical representation of the log() function

Syntax

log(number, base)

Parameter

This function requires two parameters:

  • A numberwhich must be greater than 0 for which logarithm is to be calculated.
  • The base of the logarithma number (which must be greater than one) is an optional parameter.

Return value

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

The log() function calculates the natural logarithm of a number if the base is not provided, i.e., log(y,e).

Example

#number without base
print "log(10) : ", Math.log(10), "\n"
#number with base
print "log(3,3) : ", Math.log(3,3), "\n"
#errors
#base is 0 and number is 0
print "log(0,0) : ", Math.log(0,0), "\n"
#base is 0
print "log(3,0) : ", Math.log(3,0), "\n"
#number is 0
print "log(0) : ", Math.log(0), "\n"

Free Resources