Search code examples
pythonnumpyvectorizationnumpy-ndarray

Numpy how to use np.cumprod to vectorize python for i in range function


I have two python functions. The first one:

import numpy as np
import math
mt = np.array([1, 2, 3, 4, 5, 6, 7])
age, interest = 3, 0.5

def getnpx(mt, age, interest):
    val = 1
    initval = 1
    for i in range(age, 7):
        val = val * mt[i]
        intval = val / (1 + interest) ** (i + 1 - age)
        initval = initval + intval
    return initval

The output is:

214.03703703703704

In order to make it faster, I used numpy to vectorize it:

def getnpx_(mt, age, interest):
    return 1 + (np.cumprod(mt[age:7]) / (1 + interest)**np.arange(1, 8 - age)).sum()

getnpx_(mt, age, interest)

It works and the output is still:

214.03703703703704

However I have no idea how to vectorize my another function by numpy:

def getnpx2(mt, age, interest):
    val = mt[age]
    initval = 1
    for i in range(age + 2, 8):
        val *= mt[i - 1]
        intval = val / (1 + interest) ** (i - age - 1) / mt[age]
        initval = initval + intval
    return initval

Any friend can help?


Solution

  • Your function is:

    def getnpx_(mt, age, interest):
        return (np.cumprod(mt[age:7]) / (1 + interest)**np.arange(7 - age)).sum() / mt[age]