Python math.log() – Natural Logarithm

Contents

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

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)``````
Copy

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)``````
Copy

Output

``ValueError: math domain error``

Natural logarithm of infinity.

Python Program

``````import math

x = math.inf
result = math.log(x)
print('log(x) :', result)``````
Copy

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)``````
Copy

Output

``log(x) : 5.0``

Summary

In this Python Examples tutorial, we learned the syntax of, and examples for math.log() function.

Related Tutorials

Code copied to clipboard successfully 👍