Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy: calculate based on previous element?

Tags:

python

numpy

Say that I have array x and y:

x = numpy.array([1,2,3,4,5,6,7,8,9,10])  # actual content is the a result of another calculation step

There's a formula for y, and each element is based on the previous element, let i denote the index of y, each element is:

y[i] = y[i-1] * 2 + x[i]

When calculating the first element, let y[i-1] = 50. In other words, y should be:

[101, 204, 411, 826, 1657, 3320, 6647, 13302, 26613, 53236]

How do I calculate y with numpy?

like image 825
He Shiming Avatar asked May 06 '15 05:05

He Shiming


1 Answers

Perhaps the fastest and most concise way is to use scipy.signal.lfilter, which implements exactly the kind of recursive relationship you described:

from scipy.signal import lfilter
import numpy as np

x = np.array([1,2,3,4,5,6,7,8,9,10])

b = [1., 0.]
a = [1., -2.]
zi = np.array([2*50])  # initial condition
y, _ = lfilter(b, a, x, zi=zi)

Result will be np.float64, but you can cast to e.g. np.int32 if that's what you need:

>>> y.astype(np.int32)
array([  101,   204,   411,   826,  1657,  3320,  6647, 13302, 26613, 53236])
like image 191
nirvana-msu Avatar answered Sep 20 '22 15:09

nirvana-msu