0

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?

William
  • 3,724
  • 9
  • 43
  • 76

1 Answers1

2

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

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • Thank you for your right answer,it works,can you also help this one https://stackoverflow.com/questions/69457867/numpy-how-to-use-np-cumprod-to-vectorize-python-for-i-in-range-function?noredirect=1#comment122769618_69457867 – William Oct 06 '21 at 02:11
  • Hi friend can you help me with this one ? https://stackoverflow.com/questions/69484626/numpy-operands-shape-error-after-vectorizing-function-cumprod-and-sum-invol – William Oct 07 '21 at 16:23