Log to the base 2 in Python

In this tutorial, we will learn how to calculate log to the base 2 in Python. There are various inbuilt logarithmic functions under module “math” in Python. Math module is a standard module available in Python. To use the math module, we need to import it using import math.

import math

Various inbuilt functions provided by Python for calculating log :

  • log(number,(base)): This method calculates natural log e. If the Base is not specified it calculates the natural logarithm otherwise it calculates the log of the number to the desired base. It computes value using formula : log(number)/log(Base).
  • log2(number): This method returns logarithm base 2 of a number.
  • log10(number): This method calculates the logarithm of a number to base 10.
  • log1p(number): This method calculates the logarithm of 1+number. Therefore it returns log(1+number)

The functions throw ValueError if we pass a negative number as an argument. This error occurs when the argument passed is of the right type but the value is not appropriate.

Calculating Log base 2 of a number:  log(number,(base)) method

Step 1: Import math module.

Step 2 : Take input from user using input() function. input() function converts input given to a string. Therefore, typecast the input to float value before using it.

Step 3: Calculate log to base 2 using a log(number,2) method.

Step 4: Print answer.

Code will look like this :

import math
a = float(input("Enter number whose log is to be calculated:"))
b = math.log(a,2) 
print(b)

Output:

The number entered is 2.056.

Enter number whose log is to be calculated:
 1.039840264531791

Now, If a negative number is entered, the following error occurs.

import math
a = -2 ;
b= math.log(a,2)
print('\n',b)
Traceback (most recent call last):
  File "/home/679c83ff8b1d118ad277a1fa6f07cfe2.py", line 4, in <module>
    b= math.log(a,2)
ValueError: math domain error

Calculating log base 2: log2(number) method

Use math.log2(number) instead of using math.log(number,base).

import math
a = float(input("Enter number whose log is to be calculated:"))
b= math.log2(a)
print('\n',b)

The output will look like this if the number entered is 2.056

Enter number whose log is to be calculated:
 1.039840264531791

Now, let’s see what happens if a negative number is entered in the above code.

import math
a = -2 ;
b= math.log2(a)
print('\n',b)
Traceback (most recent call last): 
File "/home/d62f7300d103f5404020a91536b586b7.py", line 4, in <module> 
b= math.log2(a) 
ValueError: math domain error

Therefore, some inbuilt methods are discussed in this article to calculate the log of a number to base 2. And both of these functions throw Value Error when a negative number is passed as an argument.

Leave a Reply

Your email address will not be published. Required fields are marked *