He Shiming - 7 months ago 33
Python Question

# Numpy: calculate based on previous element?

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?

Lets build a few of the items in your sequence:

``````y[0] = 2*y[-1] + x[0]
y[1] = 2*y[0] + x[1] = 4*y[-1] + 2*x[0] + x[1]
y[2] = 2*y[1] + x[2] = 8*y[-1] + 4*x[0] + 2*x[1] + x[2]
...
y[n] = 2**(n+1)*y[-1] + 2**n*x[0] + 2**(n-1)*x[1] + ... + x[n]
``````

It may not be immediately obvious, but you can build the above sequence with numpy doing something like:

``````n = len(x)
y_1 = 50
pot = 2**np.arange(n-1, -1, -1)
y = np.cumsum(pot * x) / pot + y_1 * 2**np.arange(1, n+1)
>>> y
array([  101,   204,   411,   826,  1657,  3320,  6647, 13302, 26613, 53236])
``````

The down side to this type of solutions is that they are not very general: a small change in your problem may render the whole approach useless. But whenever you can solve a problem with a little algebra, it is almost certainly going to beat any algorithmic approach by a far margin.

Source (Stackoverflow)