Search code examples
pythonsympycomplex-numbersgamma-function

How could I enhance the speed of this gamma function and complex numbers - related code?


Context: I am trying to make a very simple gamma function fractal plotting using Python and sympy, initially a very simple version to understand how it works (two mapping colors based on the value of counter=0 or 1).

Basically the code (below) calls to the gamma function, and then makes some complex number comparisons: just checks that the complex number "nextcomplex=gamma(mycomplex)" is closer to "1+0i" than the initial "mycomplex" complex number. The final algorithm to make the fractal is more elaborated than that, but the basic calculations are like those ones, so I would need to enhance the speed of that simple code.

For small intervals it works fine and I can plot the values, but is very slow for big intervals, I am running it right now and it is more than 1 hour and still running for an total of test_limitn x test_limitm=1000x1000 elements. (for instance up to 100x100 goes fine and I can plot the values and see a very basic fractal)

My question is: how could I enhance the code to make it faster? (e.g. other Python libraries, or there are other functions much better to do the comparisons, etc.)

from sympy import gamma,I,re,im,zoo
test_limitn = 1000
test_limitm = 1000
for m in range(-test_limitm,test_limitm):
    for n in range(-test_limitn, test_limitn):          
        counter = 0
        mycomplex = m+(n*I)
        nextcomplex = gamma(mycomplex).evalf(1) 
        if mycomplex!=zoo and nextcomplex!=zoo:
            absrenextcomplex = re(nextcomplex)
            absimnextcomplex = abs(im(nextcomplex))

            if (abs(n) > absimnextcomplex) and (abs(1-m) > abs(1-absrenextcomplex)):
                counter = 1

Any hint is very welcomed, thank you!


Solution

  • If you are only doing things numerically, you will be much better off using a numerical library like NumPy. SymPy is designed for symbolic calculations, and although it can perform numeric calculations, it isn't very fast at it.

    Beyond that, numba may be able to improve the performance of your loops.