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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)