How to use math.log() function in Python
In this article, you will learn about how to use the math.log() function in Python.
In the Python programming language, you will get the math
module that is available and you can perform many math-related actions with this module. In this module, you will get some inbuild logarithmic functions that will allow you to calculate logs. To compute logs this module provides some functions like log2(x)
, log10(x)
, log(x, Base)
, log1p(x)
. We will explore these functions in this article and work with these functions we need to import the math module into our program. Let’s start with the log log2(x) function.
log2(x) Function
This function simply computes the logarithm base 2
of x. It will simply show an error if the value of x is negative. So, we need to give a positive value always. See the below code example where we will calculate the logarithm base 2 of 100.
# Import the Math Module.
import math
# Calculating the logarithm base 2 of 100
print (math.log2(100))
# Output: 6.643856189774724
Here, you can see that we simply import the math module and calculate the logarithm base 2 of 100 in a single line.
log10(x) Function
If you need to calculate the value of x on the basis of logarithm base 10
then you can simply use the log10(x)
function. Let’s calculate the logarithm base 10 of 100 in the below section:
# Import the Math Module.
import math
# Calculating the logarithm base 10 of 100
print (math.log10(100))
# Output: 2.0
Here, you can see that the function is similar to the previous one but the only difference is the base is 10 in this case.
log(x, Base) Function
The log(x, Base)
function simply computes the logarithm of the desired base of argument and if there is no argument passed as a base then it will simply calculate the natural logarithm of x. See the below code example to understand it more clearly.
# Import the Math Module.
import math
# Calculating the logarithm without base
print (math.log(100))
# Calculating the logarithm with base 10 of 100
print (math.log(100,10))
# Output:
# 4.605170185988092
# 2.0
Here, you can see that in the first case we didn’t apply any base of x and in the second case we added the base 10 of x.
log1p(x) Function
The log1p(x)
function simply calculates the logarithm x with add 1. Let’s see an example of this function in the following section:
# Import the Math Module.
import math
# Calculating the log(1+x) of 100
print (math.log1p(100))
# Output: 4.61512051684126
Here, in the output, you can see the value of log1p(x)
and these are some useful functions for calculating logarithm. You may calculate the value with a single line of code with the help of the math
module by following these approaches.