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

Question:

exp means exponential function. Why do numpy creators introduce this function again?

Asked By: Ka Wa Yip

||

Answers:

The math.exp works only for scalars, 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.

Answered By: Srivatsan

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

Answered By: Chinmay Kanchi

If you manually vectorize math.exp using map, it is faster than numpy. As far as I tested..

%timeit np.exp(arr)

500 µs ± 3.37 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit map(math.exp, arr)

148 ns ± 4 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Answered By: Z Che
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.