Log functions in Python



In this article, we will learn about Log functions in Python 3.x. Or earlier. Here we will observe about different form of log values will different bases. Now let’s discuss about using log functions in the Python standard library.

Here is the example to illustrate the different form of log functions available in Python language.

First, let’s look at how to use the math module

>>> import math

After importing we are able to use all functions available in the math module.

Now let’s look at the implementation.

Example

import math
# log base e
print ("Natural log of 56 is : ",math.log(56))
# log base 8
print ("Log base 8 of 64 is : ",math.log(64,8))
#log base 2
print ("Log base 2 of 12 is : ",math.log2(12))
# log base 10
print ("Log base 10 of 64 is : ",math.log10(64))
# log base value+1
print ("Logarithm 5 value of 4 is : ",math.log1p)4))

Output

Natural log of 56 is : 4.02535169073515
Log base 8 of 64 is : 2.0
Log base 2 of 12 is : 3.584962500721156
Log base 10 of 64 is : 1.806179973983887
Logarithm 5 value of 4 is : 1.6094379124341003

Error handling in case of log function −

When we specify any negative value inside the log function value error is raised. This is beacuse the logarithm of negative value iis not defined in the domain of math.

Let’s try executing the function for a negative value −

Example

import math
# log base e
print ("Natural log of 56 is : ",math.log(56))
# log base 8
print ("Log base 8 of 64 is : ",math.log(64,8))
#log base 2
print ("Log base 2 of 12 is : ",math.log2(12))
# log base 10
print ("Log base 10 of 64 is : ",math.log10(64))
# log base value+1
print ("Logarithm 5 value of 4 is : ",math.log1p)4))

Conclusion

In this article, we learnt about Log functions in Python in Python 3.x. Or earlier


Advertisements