I would like to fill a numpy array with values using a function. I want the array to start with one initial value and be filled to a given length, using each previous value in the array as the input to the function.
Each array value i should be (i-1)*x**(y/z).
After a bit of work, I have got to:
import numpy as np
f = np.zeros([31,1])
f[0] = 20
fun = lambda i, j: i*2**(1/3)
f[1:] = np.fromfunction(np.vectorize(fun), (len(f)-1,1), dtype = int)
This fills an array with
[firstvalue=20, 0, i-1 + 1*2**(1/3),...]
I have arrived here having read
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.fromfunction.html
Most efficient way to map function over numpy array
Fastest way to populate a matrix with a function on pairs of elements in two numpy vectors?
How do I create a numpy array using a function?
But I'm just not getting how to translate it to my function.
fromfunctiondoes not help you do iterative code. It just applies the function to the whole set of indices (with 1 call).vectorizealso isn't helpful. It's just a convenient way of broadcasting multiple arrays to a function that only takes scalars. Neither of these promise speed.for i in np.linspace(1,len(f)-1,len(f)-1, dtype=int): f[i] = f[i-1]*2**(1/3)numpy; but they've since addedjitcompilation, that reduces the need to think in terms of whole arrays. ``numba` andcythoncan be used to the same effect.