I'm wondering when is it appropriate to use math.exp
versus np.exp
? In general, when can and should one use methods from the math module versus numpy during vectorization operations?
For example, the below snippet generates an error due to the use of math.exp
:
z = np.random.standard_normal((11, 10000))
s = np.zeros_like(z)
s[0] = 10
dt = 1/10
v = 0.25
r=0
s[1] = s[0]*math.exp((r - v ** 2 / 2)*dt + v * math.sqrt(dt) * z[1])
s[1]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-250-ce2a501848b9> in <module>
----> 1 s[1] = s[0]*math.exp((r - v ** 2 / 2)*dt + v * math.sqrt(dt) * z[1])
2 s[1]
TypeError: only size-1 arrays can be converted to Python scalars
When I replace, math.exp
with np.exp
, I obtain the desired results. However, I'm unsure why math.sqrt
in the second part of the equation didn't generate a similar error?
s[1] = s[0]*np.exp((r - v ** 2 / 2)*dt + v * math.sqrt(dt) * z[1])
s[1]
array([ 8.845, 11.254, 10.881, ..., 8.994, 8.672, 9.614])