Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use numpy to calculate a series effectively?

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?

like image 776
Alexander Avatar asked Feb 21 '12 13:02

Alexander


People also ask

What makes computation on NumPy arrays so fast?

Computation on NumPy arrays can be very fast, or it can be very slow. The key to making it fast is to use vectorized operations, generally implemented through NumPy's universal functions (ufuncs).

Is NumPy more efficient than list?

NumPy Arrays are faster than Python Lists because of the following reasons: An array is a collection of homogeneous data-types that are stored in contiguous memory locations. On the other hand, a list in Python is a collection of heterogeneous data types stored in non-contiguous memory locations.

How efficient is NumPy?

Because the Numpy array is densely packed in memory due to its homogeneous type, it also frees the memory faster. So overall a task executed in Numpy is around 5 to 100 times faster than the standard python list, which is a significant leap in terms of speed.

Why is NumPy more efficient?

NumPy arrays facilitate advanced mathematical and other types of operations on large numbers of data. Typically, such operations are executed more efficiently and with less code than is possible using Python's built-in sequences.


1 Answers

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])
like image 175
Sven Marnach Avatar answered Oct 05 '22 22:10

Sven Marnach