Python math.log() function


The math.log() function in Python is used to calculate the logarithm of a number. You can compute logarithms with different bases using this function, with the default base being ee (Euler's number, approximately 2.71828).

Syntax

import math result = math.log(x[, base])
  • x: The number for which you want to calculate the logarithm. It must be a positive number.
  • base (optional): The base of the logarithm. If not provided, the natural logarithm (base ee) is calculated.

Return Value

  • Returns the logarithm of x to the specified base. If no base is specified, it returns the natural logarithm of x.

Examples

  1. Calculating the natural logarithm (base ee):

    import math result = math.log(10) print(result) # Output: 2.302585092994046 (approximately)
  2. Calculating the logarithm with a specified base: For example, calculating the logarithm of 1000 with base 10:

    result = math.log(1000, 10) print(result) # Output: 3.0 (because 10^3 = 1000)
  3. Using base 2 for binary logarithm:

    result = math.log(8, 2) print(result) # Output: 3.0 (because 2^3 = 8)
  4. Handling values less than or equal to zero: If you try to calculate the logarithm of a non-positive number, a ValueError will be raised.

    try: result = math.log(-5) except ValueError as e: print(e) # Output: math domain error
  5. Using logarithms in expressions: You can use the math.log() function in more complex mathematical expressions:

    value = 20 result = math.log(value) + 5 print(result) # Output: 7.302585092994046 (approximately)

Summary

  • The math.log() function computes the logarithm of a positive number.
  • You can specify a custom base; if not provided, it calculates the natural logarithm (base ee).
  • The return type is always a float.
  • This function is essential in various mathematical and scientific computations, including growth models, finance, and information theory.