Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

exp means exponential function

exp in math module: https://docs.python.org/2/library/math.html

exp in numpy module: http://docs.scipy.org/doc/numpy/reference/generated/numpy.exp.html

Why do numpy creators introduce this function again?

like image 549
Ka-Wa Yip Avatar asked Jun 08 '15 14:06

Ka-Wa Yip


People also ask

What is the difference between NumPy and math?

math is part of the standard python library. It provides functions for basic mathematical operations as well as some commonly used constants. numpy on the other hand is a third party package geared towards scientific computing. It is the defacto package for numerical and vector operations in python.

What is NumPy exp in Python?

The exp function in NumPy is used to compute the exponent of all values present in the given array. e refers to Euler's constant. It has an approximate value of 2.718.

What is math exp in Python?

The math. exp() method returns E raised to the power of x (Ex). 'E' is the base of the natural system of logarithms (approximately 2.718282) and x is the number passed to it.

Is NumPy a math library?

NumPy contains a large number of various mathematical operations. NumPy provides standard trigonometric functions, functions for arithmetic operations, handling complex numbers, etc. NumPy has standard trigonometric functions which return trigonometric ratios for a given angle in radians.


1 Answers

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.

like image 54
Srivatsan Avatar answered Sep 20 '22 18:09

Srivatsan