The Python LOG2 function is one of the Python Math function which is used to calculate the logarithmic value of given number of base 2.
In this article we will show you, How to use LOG2() function in Python Programming language with example.
TIP: This function is more accurate than math.log(x, 2). Please refer Python LOG article to understand the log function.
Syntax of a Python LOG2 Function
The basic syntax of the LOG2 Function in Python Programming Language is as shown below:
Math.log2(number);
Number: It can be a number or a valid numerical expression.
- If the number argument is positive number, LOG2() function will return the output.
- If the number argument is Negative number, LOG2() function will return ValueError
- When the number argument is Zero, Python LOG2() function will return ValueError
- If the number argument is not a number, LOG2() function will return TypeError.
Python LOG2 Function Example
The Python LOG2 Function is used to calculate the logarithmic value of given number of base 2.
In this example, We are going to check the same with different data types and display the output
PYTHON CODE
# Python LOG2 Function import math Tup = (10, 20, 30, -40 , 50) # Tuple Declaration Lis = [-1, 2, 3.5, -43 , 50] # List Declaration print('Logarithm value of Positive Number = %.2f' %math.log2(5)) print('Logarithm value of Positive Decimal = %.2f' %math.log2(2.5)) print('Logarithm value of Tuple Item = %.2f' %math.log2(Tup[2])) print('Logarithm value of List Item = %.2f' %math.log2(Lis[2])) print('Logarithm value of Multiple Number = %.2f' %math.log2(2 + 7 - 5)) print('Logarithm value of String Value = ', math.log2('Python'))
OUTPUT
ANALYSIS
- In this Python log2 function example, At the beginning, We declared Python List and Tuple with some random values.
- Within the first two statements, We used the LOG2() Function directly on Positive integer and Decimal values.
- Next two statements, We used the LOG2() Function on Python Tuple and List items. If you observe the above screenshot, LOG2() function is calculating the logarithm value of base 2.
- Next statement, We tried Python LOG2() Function with multiple values
- Next statement, We tried LOG2() Function on String value. As we said before, this will return TypeError: a float is required as output
- Next, We tried LOG2() Function on Zero value. As we said before, this is returning ValueError: math domain error as output
- Last, We tried LOG2() Function on Negative value. As we said before, this is returning ValueError: math domain error as output
Thank You for Visiting Our Blog