Python log(x, base) function is used to compute a’s natural logarithm (base e). If 2 arguments are passed, it computes the logarithm of the desired base of argument a, numerically value of log(a)/log(Base).
Python log(x, base)
Python log(x, base) is a built-in function used to get the essential logarithm function. The log() function is used to get a log of x of a particular base. Unfortunately, the log() function is under the math library, so we need to import the math library to use the log() function.
Syntax
math.log(num, Base)
Arguments
This function takes two arguments:
num -> whose log we want to find
Base -> with which base do we want to find a log
Return Value
This function can return two types of values:
- Return natural value if only 1 argument is passed.
- Return the log with specified based if two arguments are passed.
But the log(x, base) function throws a ValueError exception if any value is passed as an argument.
Example
See the following code.
# Importing math library import math # initializing values num = 15 base = 5 print("Natural log of ", num, " is: ", math.log(num)) print("The logarithm of ", num, " of the base ", base, " is: ", math.log(num, base))
Output
Natural log of 15 is: 2.70805020110221 The logarithm of 15 of the base 5 is: 1.6826061944859854
In this program, we initialized the value, then calculated the natural logarithm of the number, and in the next line, we calculated the logarithm of base 5.
Example 2
See the following code.
# Importing math library import math # By taking input from user num = int(input("Enter the number: ")) base = int(input("Enter the base: ")) print("Natural log of ", num, " is: ", math.log(num)) print("Logarithm of base ", base, " of the number ", num, " is: ", math.log(num, base))
Output
Enter the number: 12 Enter the vase: 8 Natural log of 12 is: 2.4849066497880004 Logarithm of base 8 of the number 12 is: 1.1949875002403856
In this program, we have taken input from the user, then calculated the natural logarithm of the number, and in the next line, we calculated the logarithm of base 8.
Conclusion
Python offers many built-in logarithmic functions under the module “math”, which allows us to compute logs using a single line. In the math module, two positions for calculating logarithmic values are defined. The log() function returns the natural logarithm of the number, whereas log10() calculates the standard logarithm, i.e., to the base 10.