Python log1p(x) Function: The Complete Guide

Python log1p(x) function is used to get the logarithm(1+num) function. The log1p(x) function is under the math library, so we need to import the math library to use this function.

Python log1p(x)

The log1p() is a built-in Python function defined under the math module, and it is used to get the natural logarithm of 1+x (base e); it accepts a number and returns the natural logarithm 1+number on the base e.

If we provide anything else except a number, the method returns a “TypeError: a float is required“.

Syntax

math.log1p(num)

Arguments

The log1p(num) function takes only one argument:

The num -> whose log(1+num) we want to find.

Return Value

The log1p(x) function can return only one type of value log(1+a). But this 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

# positive value
num = 16
print("Logarithm(1+a) of the value ", num, " is: ", math.log1p(num))

# Negative number
num = -10
print("Logarithm(1+a) of the value ", num, " is: ", math.log1p(num))

Output

Logarithm(1+a) of the value  16  is:  2.833213344056216
Traceback (most recent call last):
  File "log1p1.py", line 12, in <module>
	print("Logarithm(1+a) of the value ",num," is: ",math.log1p(num))
ValueError: math domain error

In this program, we have first initialized the value, then calculated the logarithm(1+a) of the number, and in the next line, we have initialized one negative value. We can see that the program returned us a ValueError.

Example 2

See the following code.

# Importing math library
import math

# taking input from user values

# positive value
num = int(input("Enter a num to find log(1+a): "))
print("Logarithm(1+a) of the value ", num, " is: ", math.log1p(num))

Output

Enter a num to find log(1+a): 15
Logarithm(1+a) of the value  15  is:  2.772588722239781

In this program, we have taken input from the user; then, we have calculated the logarithm(1+a) of 15.

Conclusion

Python math.log1p() function is used to get the natural logarithm of 1+x (base e); it accepts a number and returns the natural logarithm of 1+number on the base e.

See also

Python log(x, base)

Python exp()

Python trunc()

Python absolute value

Python fabs()

Leave a Comment

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