Ruby Tutorial Ruby References

Ruby - Math.log() Method



The Ruby Math.log() method returns the natural logarithm (base e) or logarithm to the specified base of a given number.

Syntax

Math.log(x, base)

Parameters

x Required. Specify the number.
base Optional. Specify the base. Default is e.

Return Value

Returns the natural logarithm or logarithm to the specified base of a given number.
If the x or base is negative, DomainError is thrown.
If the x is 0, it returns -Infinity.

Example:

In the example below, Math.log() method is used to calculate the natural logarithm of a given number.

puts "Math.log(1) = #{Math.log(1)}" 
puts "Math.log(Math::E) = #{Math.log(Math::E)}"
puts "Math.log(10) = #{Math.log(10)}"
puts "Math.log(0) = #{Math.log(0)}"

The output of the above code will be:

Math.log(1) = 0.0
Math.log(Math::E) = 1.0
Math.log(10) = 2.302585092994046
Math.log(0) = -Infinity

Example:

In this example, Math.log() method is used to calculate the specified base logarithm of a given number.

puts "Math.log(2, 2) = #{Math.log(2, 2)}"
puts "Math.log(81, 3) = #{Math.log(81, 3)}"
puts "Math.log(100, 10) = #{Math.log(100, 10)}"

The output of the above code will be:

Math.log(2, 2) = 1.0
Math.log(81, 3) = 4.0
Math.log(100, 10) = 2.0

❮ Ruby Math Module