Ruby Tutorial Ruby Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Ruby - Math.log2() Method



The Ruby Math.log2() method returns the base-2 logarithm of a given number.

Syntax

Math.log2(x)

Parameters

x Specify the number.

Return Value

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

Example:

In the example below, Math.log2() method is used to calculate the base-2 logarithm of a given number.

puts "Math.log2(1) = #{Math.log2(1)}"
puts "Math.log2(2) = #{Math.log2(2)}"
puts "Math.log2(10) = #{Math.log2(10)}"
puts "Math.log2(0) = #{Math.log2(0)}"

The output of the above code will be:

Math.log2(1) = 0.0
Math.log2(2) = 1.0
Math.log2(10) = 3.321928094887362
Math.log2(0) = -Infinity

❮ Ruby Math Module

5