I have a python function:
pval = np.array([1,1,1,1,1,0.999709, 0.99973,0.999743,0.999706, 0.999675, 0.99965, 0.999629])
age1=4
age2=8
def getnpxtocert(mt, age, age2):
val = mt[age]
for i in range(age 1,age2):
val = val * mt[i]
return val
getnpxtocertv(pval,age1,age2)
The output is:
0.9991822227268075
And then I tried to use cumprod to vectorize it:
def getnpxtocertv(mt, age, age2):
return (mt[age]*np.cumprod(mt[age 1:age2])).sum()
getnpxtocert(pval,age1,age2)
But the output is:
2.998330301296807
What did I wrong?Any friend can help?
CodePudding user response:
You don't need cumprod
and sum
. Just use prod
:
def getnpxtocert_v2(mt, age, age2):
return np.prod(mt[age:age2])
Comparison:
In [23]: getnpxtocert(pval, age1, age2)
Out[23]: 0.9991822227268075
In [24]: getnpxtocert_v2(pval, age1, age2)
Out[24]: 0.9991822227268075
cumprod
takes an array [x0, x1, x2, ...]
and returns an array with the same length containing [x0, x0*x1, x0*x1*x2, ...]
. prod
returns the scalar that is the product of all the elements x0*x1*x2*...
.