Math expm1() method in Python math library
There are many mathematical methods in the Python math library. The method that we will be talking about today is the expm1() method. This method is used to find the value of exp(x) – 1. Now, you might be thinking, why we need another function to calculate the value of exp(x) – 1 as we already have exp() method.
We can simply compute the value of exp(x) and then subtracts 1 from the result. The answer to this question is that this method is much more accurate in results when the value of x becomes very small. We will see an example program to understand the difference between these two further in this tutorial.
The syntax for this method is as follows:
x is the number for which we need to calculate the value of exp(x) – 1.
Let us understand this function better with the following example program.
import math x = 2 print("expm1(2) = ", math.expm1(2)) x = -2 print("expm1(-2) = ", math.expm1(-2))
expm1(2) = 6.38905609893065 expm1(-2) = -0.8646647167633873
These are the values of exp(2) – 1 and exp(-2) – 1 respectively.
Difference between exp() – 1 and expm1() with an example program
Let’s say we have a very small number x. Now if we compute the value of exp(x) – 1 and expm1(x), the values returned may differ slightly with expm1() returning more accurate output. In mathematics, there are many instances when we need to calculate the value of exp(x) -1. Using expm1() can be useful in such scenarios.
Have a look at the given code and try to understand the difference between these two.
import math x = 2e-10 # a very small number print("exp(x)-1 = ", math.exp(x) - 1) print("expm1(x) = ", math.expm1(x))
exp(x)-1 = 2.000000165480742e-10 expm1(x) = 2.0000000002000002e-10
I hope this post was helpful to you. Thank you.
Also read: Math module of Python