Skip to content Skip to sidebar Skip to footer

Numpy Array Fromfunction Using Each Previous Value As Input, With Non-zero Initial Value

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

Solution 1:

Except for the initial 20, this produces the same values

np.arange(31)*2**(1/3)

Your iterative version (slightly modified)

deffoo0(n):
    f = np.zeros(n)
    f[0] = 20for i inrange(1,n): 
        f[i] = f[i-1]*2**(1/3)
    return f

An alternative:

deffoo1(n):
    g = [20]
    for i inrange(n-1):
        g.append(g[-1]*2**(1/3))
    return np.array(g)

They produce the same thing:

In [25]: np.allclose(foo0(31), foo1(31))
Out[25]: True

Mine is a bit faster:

In [26]: timeit foo0(100)35 µs ± 75 ns per loop(mean ± std. dev. of 7 runs, 10000 loops each)
In [27]: timeit foo1(100)23.6 µs ± 83.6 ns per loop(mean ± std. dev. of 7 runs, 10000 loops each)

But we don't need to evaluate 2**(1/3) every time

def foo2(n):
    g = [20]
    const = 2**(1/3)
    for i in range(n-1):
        g.append(g[-1]*const)
    return np.array(g)

minor time savings. But that's just multiplying each entry by the same const. So we can use cumprod for a bigger time savings:

def foo3(n):
    g = np.ones(n)*(2**(1/3))
    g[0]=20
    return np.cumprod(g)

In [37]: timeit foo3(31)
14.9 µs ± 14.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [40]: np.allclose(foo0(31), foo3(31))
Out[40]: True

Post a Comment for "Numpy Array Fromfunction Using Each Previous Value As Input, With Non-zero Initial Value"