1

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).

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?

Community
  • 1
  • 1
rappr
  • 135
  • 7

1 Answers1

2

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

cel
  • 30,017
  • 18
  • 97
  • 117
  • I have not tried Cython yet - if your code ran in 037 seconds it seems very interesting. I have written a mex file for Matlab and, surprisingly enough, it is slower than the code in Matlab (!). – rappr May 29 '15 at 11:08
  • 1
    Yes, Cython or Pypy seem to be the simplest approach here, since your loop can't be vectorized. You can't say if it slower than Matlab + .mex before trying it on your computer since it is system and compiler dependent. – rth May 30 '15 at 17:23