5

I want to create an array in numpy that contains the values of a mathematical series, in this example the square of the previous value, giving a single starting value, i.e. a_0 = 2, a_1 = 4, a_3 = 16, ...

Trying to use the vectorization in numpy I thought this might work:

import numpy as np
a = np.array([2,0,0,0,0])
a[1:] = a[0:-1]**2

but the outcome is

array([2, 4, 0, 0, 0])

I have learned now that numpy does internally create a temporary array for the output and in the end copies this array, that is why it fails for the values that are zero in the original array. Is there a way to vectorize this function using numpy, numexpr or other tools? What other ways are there to effectively calculate the values of a series when fast numpy functions are available without going for a for loop?

Alexander
  • 2,174
  • 3
  • 16
  • 25
  • also related: http://stackoverflow.com/questions/4407984/is-a-for-loop-necessary-if-elements-of-the-a-numpy-vector-are-dependant-upon-t – sdaau Dec 18 '13 at 11:16

1 Answers1

6

There is no general way to vectorise recursive sequence definitions in NumPy. This particular case is rather easy to write without a for-loop though:

>>> 2 ** 2 ** numpy.arange(5)
array([    2,     4,    16,   256, 65536])
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841