Python math log2 function is used to get the logarithm of a given number, raised to a base 2. The log2 function is a built-in function and it returns the base-2 logarithm of a float value.
math.log2(x)
In some scenarios the return values of the log2
function:
- If we pass a positive number then the function returns the correct output.
- In case we pass a negative number then the log2 function raises a ValueError exception and returns the same.
- If pass some non-numeric then the log2log2 function returns the TypeError exception.
Python math log2 function example
Simple example code Calculating Logarithm using log2 in Python.
import math # Positive Number print(math.log2(64)) print(math.log2(2.7183)) print(math.log2(2)) print(math.log2(1)) # Negative Number # print(math.log2(-32)) # ValueError # Non-numeric Value # print(math.log2('a')) # TypeError
Output:
Do comment if you have any doubts or suggestions on this Python math module topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.