exp
means exponential function. Why do numpy
creators introduce this function again?
What is the difference between math.exp and numpy.exp and why do numpy creators choose to introduce exp again?
42.4k Views Asked by Ka Wa Yip At
3
There are 3 best solutions below
1

math.exp
works on a single number, the numpy version works on numpy arrays and is tremendously faster due to the benefits of vectorization. The exp
function isn't alone in this - several math
functions have numpy counterparts, such as sin
, pow
, etc.
Consider the following:
In [10]: import math
In [11]: import numpy
In [13]: arr = numpy.random.random_integers(0, 500, 100000)
In [14]: %timeit numpy.exp(arr)
100 loops, best of 3: 1.89 ms per loop
In [15]: %timeit [math.exp(i) for i in arr]
100 loops, best of 3: 17.9 ms per loop
The numpy version is ~9x faster (and probably can be made faster still by a careful choice of optimized math libraries)
As @camz states below - the math
version will be faster when working on single values (in a quick test, ~7.5x faster).
The
math.exp
works only for scalars, whereasnumpy.exp
will work for arrays.Example:
It is the same case for other
math
functions.Also refer to this answer to check out how
numpy
is faster thanmath
.