Search code examples
pythonnumpygeneratorsequencelogarithm

Replace a old code by a more efficient code


I need to create a sequence of number a_t according to a old sequence of number z_t and a_0. a_t is define equal to 27 if t=0 or a(t-1)exp(z(t-1)) for t>=1.

In using generator, that code is simply

import math

def a_t(zs, a=27):
    z = next(zs)
    yield a
    for z in zs:
        a *= math.exp(z)
        yield a

It seems possible to work with a_0 only and the sum over z_t-1, z_t-2, ..., z0 instead of waiting for a_t-1 to compute a_t. So it is possible to vectorize the computation instead of computing the a_i one after the other. Is it possible to code the following sequence with numpy with purpose of vectorizating, i.e. a_t = a_0 exp(sum(z_i)) for i=0 to t-1? It is probably faster to compute as we already know the sequence z_t.


Solution

  • Yes,

    you can use np.cumsum(z) to create a and array with sum(z_i) and np.exp() on that again to calculate what you want, then just multiply that with a_0.

    a_0 = 27
    z = np.array([1,2,3])
    cs = np.cumsum(z)
    result = np.exp(cs)*a_0