Python: What is the difference between math.exp and numpy.exp and why do numpy creators choose to introduce exp again

The math.exp works only for scalars as EdChum mentions. Whereas numpy.exp will work for arrays.

Example:

>>> import math
>>> import numpy as np
>>> x = [1.,2.,3.,4.,5.]
>>> math.exp(x)

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    math.exp(x)
TypeError: a float is required
>>> np.exp(x)
array([   2.71828183,    7.3890561 ,   20.08553692,   54.59815003,
        148.4131591 ])
>>> 

It is the same case for other math functions.

>>> math.sin(x)

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    math.sin(x)
TypeError: a float is required
>>> np.sin(x)
array([ 0.84147098,  0.90929743,  0.14112001, -0.7568025 , -0.95892427])
>>> 

Also refer to THIS ANSWER to check out how numpy is faster than math.


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).