All Posts

Python log() Function

Python log() Function

Python log() function is defined in Python’s standard Math Library. To work with the function, we need to import the math module.

import math

Python log() Function

The log() function returns the natural logarithm for the input number. The general syntax of the function is as follows:

math.log(x)

Python provides another variation log1p(x) function. This function returns the natural logarithm for the 1 + x.

math.log1p(x)

Python provides the log10(x) function. This function returns the base 10 logarithm for the input number x.

math.log10(x)

Python also provides the log2(x) function. This function returns the base 2 logarithm for the input number x.

math.log2(x)

Examples

Let’s understand the function with the help of some examples.

# Python log() Function
# Python Tutorials – www.TestingDocs.com

import math

print(math.log(7.387)) # roughly 2

print(math.log10(100)) # 2

print(math.log2(8)) # 3

print(math.log1p(1.718)) # should be nearly ~ 1

Program Output

Save and run the program to view the program output.

Python log() Function

 

Using the function without importing the math module would result in the following error:

NameError: name ‘log’ is not defined

If the argument is negative or zero, the following error occurs:

ValueError: math domain error

—

Python Tutorials

Python Tutorial on this website can be found at:

https://www.testingdocs.com/python-tutorials/

More information on Python is available at the official website: