How can I use numpy to efficiently calculate a series?

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 one initial value, i.e. a_0 = 2, a_1 = 4, a_3 = 16 ...

Trying to use 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 result

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

Now I found out that numpy does the internal creation of a temporary array for output and at the end copies that array, so it fails for values ​​that are zero in the original array. Is there a way to vectorize this function using numpy, numexpr or other tools? What other methods exist for efficiently calculating series values ​​when fast numpy functions are available without going into a for loop?

+4
source share
1 answer

There is no general way to vectorize definitions of recursive sequences in NumPy. This particular case is pretty easy to write without a loop:

 >>> 2 ** 2 ** numpy.arange(5) array([ 2, 4, 16, 256, 65536]) 
+6
source

Source: https://habr.com/ru/post/1397613/


All Articles