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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your right answer,it works,can you also help this one stackoverflow.com/questions/69457867/…
Hi friend can you help me with this one ? stackoverflow.com/questions/69484626/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.