AppDividend
Latest Code Tutorials

Python log(x, base) Function Example

0

Python log(x, base) is an inbuilt function that is used to get the basic logarithm function. The log() function is used to get a log of x of a particular base. The log() function is under the math library, so we need to import the math library to use the log() function.

Python log(x, base)

Python log(x, base) function is used to compute the natural logarithm (base e) of a. If 2 arguments are passed, it computes the logarithm of the desired base of argument a, numerically value of log(a)/log(Base).

Syntax

math.log(num, Base)

This function takes two arguments:

num -> whose log we want to find

Base -> with which base we want to find a log

Return Value

This function can return two types of values:

  1. Return natural value if only 1 argument is passed.
  2. 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.

Programming 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 have first initialized the value, then we have calculated the natural logarithm of the number, and in the next line, we have 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 we have calculated the natural logarithm of the number, and in the next line, we have calculated the logarithm of base 8.

Conclusion

Python offers many inbuild logarithmic functions under the module “math,” which allows us to compute logs using a single line. In the math module, two functions for calculation of logarithmic value are defined. The log() function returns the natural logarithm of the number, whereas log10() calculates the standard logarithm i.e., to the base 10.

See also

Python exp()

Python trunc()

Python absolute value

Python fabs()

Python expm1()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.