

The main time saver in method2 and foo2 is carrying over x, the last value, from one iteration to the next, rather than indexing with returnList. of 7 runs, 100000 loops each)ġ3 µs ± 29.7 ns per loop (mean ± std. of 7 runs, 10000 loops each)ġ6.9 µs ± 103 ns per loop (mean ± std. In : timeit build_array_recursively(20,0.3, fn) Ħ1.4 µs ± 63 ns per loop (mean ± std. Return x-x*d_t+x*x/2*d_t*d_t-x*x*x/6*d_t*d_t*d_tĪnd a function that combines elements of build_array_recursively and method2: def foo1(length, V_0, function):
#NP TREAT ARRAY AS ELEMENT CODE#
Using a function to make the code clearer (instead of the inline lambda): def fn(x): In my example, the difference equation is difficult to solve manually. Is it possible to vectorize recursive calculation of a NumPy array where each element depends on the previous one?īut was not answered in general. can a Fibonacci array be constructed similarly? If so is there a way to handle two elements before the current one, e.g.

Is there a fast way of doing this in numpy without a for loop? The print method above outputs I would like to create a numpy array where the first element is a defined constant, and every next element is defined as the function of the previous element in the following way: import numpy as npĭef build_array_recursively(length, V_0, function):
