The Python log1p() function is a built-in math library function that returns the natural logarithmic value of a given number plus 1. In short, log1p(x) = log(x + 1).
The syntax of the log1p() function is
log1p(x)
Parameter: The log1p() function accepts either an integer or a floating-point number and returns the natural logarithm of x plus 1.
Return Value: It returns the base e logarithm value as a floating-point number. If the given number is negative, it returns a ValueError. When we pass a nan (Not a Number), it returns TypeError.
Python log1p() function example
In the following example, we use the log1p() function to find the natural logarithm of 1 plus 1. Here, we are using a positive integer.
import math
print(math.log1p(1))
0.6931471805599453
If we use the log() function (print(math.log(1 + 1))), it returns the same result. However, if the value is closer to 0, the log1p() function returns an accurate result. On the other hand, the log(x + 1) differs in decimal precision.
In the following example, we use the log1p() function to find the natural logarithm value of a large positive number. For more math functions, please refer to the Python page.
import math
print(math.log1p(10000))
print(math.log1p(1000000))
9.210440366976517
13.815511557963774
Using Python log1p() on Negative numbers
If the negative number is smaller, that is, greater than -1 or anything between 0 and -1 (excluding), the log1p() function calculates the logarithm value. However, if the value is less than -1, it returns a ValueError.
import math
print(math.log1p(-0.5))
print(math.log1p(-0.75))
print(math.log1p(-1))
-0.6931471805599453
-1.3862943611198906
ValueError: math domain error
Using log1p() on string data
If we use the log1p() function on a string or a non-numeric value (nan), it returns a TypeError. Please refer to the exp, log2, and log10 functions,
import math
print(math.log1p("hello"))
TypeError: must be real number, not str