Can I use numpy to speed this loop?

前端 未结 3 2024
猫巷女王i
猫巷女王i 2020-12-11 10:18

Good evening,

I am trying to speed up the loop in this code. I have read through the numpy docs but to no avail. np.accumulate looks like it is almost what I need,

3条回答
  •  猫巷女王i
    2020-12-11 11:14

    I am not sure there is much to do to speed up the loop... The only way I see would be to avoid the recursion, ie compute s2[t] "directly" for each t. But this is expensive as well...

    You have

    s2[t] = AR_part[t-1] + beta * s2[t-1]
    = AR_part[t-1] + beta * (AR_part[t-2] + beta * s2[t-2])
    = AR_part[t-1] + beta * AR_part[t-2] + beta^2 * s2[t-2]
    = np.dot( AR[:t-1], beta_powers[-(t-1):]  )
    

    Where beta_powers contains [beta^1000, beta^999, ... 1.0]. You can create beta_powers this way:

    np.power(beta, np,arange(1000))[::-1].
    

    But I can't see a way to compute that stuff faster than what your loop does...

    However you can rewrite it:

    for t in range(N):
        s2[t+1] = AR_part[t] + beta * s2[t]
    

提交回复
热议问题