I am fairly new to numpy. I have the following code, which gives me the desired result:
import numpy as np
def get_result(S,K,delS):
res=np.zeros(S.shape[0],dtype=np.float64)
for j in range(res.shape[0]):
if S[j]-K>delS:
res[j]+=np.floor((S[j]-K)/delS)
K+=np.floor((S[j]-K)/delS)*delS
elif S[j]-K<-delS:
res[j]+=np.ceil((S[j]-K)/delS)
K+=np.ceil((S[j]-K)/delS)*delS
return res
S=np.array([1.0,1.05,1.1,1.12,1.09,1.14,1.21,1.6,1.05,1.0,0.95,0.90,0.87,0.77,0.63,0.85,0.91,0.76],dtype=np.float64)
K=1.0
delS=0.1
l=get_result(S,K,delS)
for j in range(S.shape[0]):
print("%d\t%.2f\t%.0f" % (j,S[j],l[j]))
The get_result function contains a for-loop, however, and is therefore awkwardly slow for larger input vectors S. Can such a function be vectorized in numpy-syntax? Any help would be appreciated.
Kis changing in the loop. Since calculating K[j+1] requires the knowledge of K[j], there are dependencies between the iterations and the loop cannot be vectorized. Not at least to the best of my knowledge.Python 2.xreplacerange(returns list) byxrange(returns generator) for a significant speedup.