Avoid loops in the computation of logistic equation?
Question: I am trying to calculate the nth value of a logistic equation in Python. It is
easy to do it with a loop:

    
    
    import timeit
    tic = timeit.default_timer()
    
    x = 0.23
    i = 0
    n = 1000000000
    while (i < n):
        x = 4 * x * (1 - x)
        i += 1
    
    toc = timeit.default_timer()
    toc - tic
    

However it is also generally time-consuming. Doing it in PyPy greatly improves
the performance, as suggested by abarnert in [Is Matlab faster than Python
(little simple experiment)](http://stackoverflow.com/questions/30475410/is-
matlab-faster-than-python-little-simple-experiment).

I have also been suggested to avoid Python loops and use NumPy arrays and
vector operations instead - actually I do not see how these can help (it seems
to me that NumPy operations are similar to Matlab ones, and I am unaware of
any way the code above can be vectorized in Matlab either).

Is there a way to optimize the code without loops?


Answer: Without loops? Maybe,but this is probably not be the best way to go. It's
important to realize that loops are not per-se slow. You try to avoid them in
`python` or `matlab` in high performance code. If you are writing `C` code,
you don't have to care.

So one idea to optimize here would be to use `cython` to compile your code to
`C` code:

`python` version:

    
    
    def calc_x(x, n):
        i = 0
        while (i < n):
            x = 4 * x * (1 - x)
            i += 1
        return x
    

statically typed `cython` version:

    
    
    def calc_x_cy(double x, long n):
        cdef long i = 0
        while (i < n):
            x = 4 * x * (1 - x)
            i += 1
        return x
    

And all of a sudden, you are almost two orders of magnitude faster:

`%timeit calc_x(0.23, n)` -> 1 loops, best of 3: 26.9 s per loop

`%timeit calc_x_cy(0.23, n)` -> 1 loops, best of 3: 370 ms per loop

