I have a recurrent relation that looks like the following:
f_0 = s_0
f_1 = alpha * s_1 + (1 - alpha) * f_0
f_2 = alpha * s_2 + (1 - alpha) * f_1
...
f_n = alpha * s_n + (1 - alpha) * f_n-1
this is easy enough to code up as a for-loop (example code)
import numpy as np
## values for example only ##
s = np.linspace(0, 10, 3000)
alpha = 1 / 5
f = s.copy()
for i in range(1, len(s)):
f[i] = alpha * s[i] + (1 - alpha) * f[i-1]
my struggle is finding a way to vectorize this relation. I've tried being clever with slice indexing, but something like
f[1:] = alpha * s[1:] + (1 - alpha) * f[:-1]
is clearly not right, as it doesn't update f
.
Is there an obvious way to vectorize this recurrence relation? I'd rather avoid this for-loop if I can, as my code will have to do this thousands of times as part of an optimization routine.
Thanks!
Update
Thanks for the feedback. I tried a naive numba implementation @jit
and it actually made the loop 50x faster?! Being new to numba, is there any way to further tune these results?