The Python math.log2() method is used to calculate the base-2 logarithm of a given number x. It calculates the power to which 2 must be raised to obtain x. Mathematically, the method is represented as −
\log2\:(x)\:=\:\log_{2}({x})
In other words, if log2(x) = y, then 2y = x. For example, if x = 8, then math.log2(8) returns 3 because 23 = 8.
Note: To use this function, you need to import math module.
SyntaxFollowing is the basic syntax of the Python math.log2() method −
math.log2(x)Parameters
This method accepts either an integer or a floating-point number as a parameter for which you want to calculate the logarithm base 2.
Return ValueThe method returns the logarithm base 2 of x. The return value is a floating-point number.
Example 1In the following example, we calculate the base-2 logarithm of 8, which means passing a positive integer as an argument to the log2() method −
import math result = math.log2(8) print("The result obtained is:", result)Output
The output obtained is as follows −
The result obtained is: 3.0Example 2
Here, we pass a fractional value as an argument to the log2() method. We calculate the base-2 logarithm of 0.5 −
import math result = math.log2(0.5) print("The result obtained is:", result)Output
Following is the output of the above code −
The result obtained is: -1.0Example 3
In this example, we calculate the base-2 logarithm of 3. Since 3 is not a power of 2, the result is a decimal value −
import math result = math.log2(3) print("The result obtained is:", result)Output
We get the output as shown below −
The result obtained is: 1.584962500721156Example 4
Now, we use a variable "x" to store the argument. We then calculate the base-2 logarithm of 16 −
import math x = 16 result = math.log2(x) print("The result obtained is:", result)Output
The result produced is as shown below −
The result obtained is: 4.0
python_maths.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4