Python math.log() - Natural Logarithm
Python math.log()
math.log(x) function returns the natural logarithm of x.
We may also specify an optional base value to the log() function for calculating logarithm of x.
Syntax
The syntax to call log() function is
math.log(x, base)
where
Parameter | Required | Description |
---|---|---|
x | Yes | A numeric value. The value must be greater than 0. |
base | No | A numeric value. The base value for logarithm calculation. The default value is e. |
If x is an invalid value, such as a negative value, then log() raises ValueError.
Examples
In the following program, we find the natural logarithm of 2, using log() function of math module.
Python Program
import math
x = 2
result = math.log(x)
print('log(x) :', result)
Output
log(x) : 0.6931471805599453
Natural logarithm of a negative number.
Python Program
import math
x = -2
result = math.log(x)
print('log(x) :', result)
Output
ValueError: math domain error
Natural logarithm of infinity.
Python Program
import math
x = math.inf
result = math.log(x)
print('log(x) :', result)
Output
log(x) : inf
Logarithm of 1024 to base 4.
Python Program
import math
x = 1024
base = 4
result = math.log(x, base)
print('log(x) :', result)
Output
log(x) : 5.0
Summary
In this Python Examples tutorial, we learned the syntax of, and examples for math.log() function.