A Real Mandelbrot Set

So far the basic kernel for our Mandelbrot Set has used python's complex data type.

def mandel_column(x,ymin,ymax,size,maxiter):
    col=np.zeros(size)
    ystep=(ymax-ymin)/size
    for j in range(0,size):
        z0=complex(x,ymax-j*ystep)
        i=0
        z=z0
        while (i<maxiter)and(z.real**2+z.imag**2<4):
            z=z*z+z0
            i=i+1
        col[j]=1-i/maxiter

    return col

This is perfect natural. Python supports the complex data type, our calculation uses it, and the result is more compact than it would otherwise be. But how might we code this if faced with a language which has no support for complex numbers, such as C before 1999 or Java (unless we add our own class for them)?

def mandel_column(x0,ymin,ymax,size,maxiter):
    col=np.zeros(size)
    ystep=(ymax-ymin)/size
    for j in range(0,size):
        y0=ymax-j*ystep
        i=0
        x=x0
        y=y0
        x2=x*x
        y2=y*y
        while (i<maxiter)and(x2+y2<4):
            y=2*x*y+y0
            x=x2-y2+x0
            x2=x*x
            y2=y*y
            i=i+1
        col[j]=1-i/maxiter

    return col

Note that it is normally necessary to use a temporary variable when performing complex multiplication.

  tmp=x
  x=x*x-y*y
  y=2*tmp*y

Here we have avoided this by storing the squares of the real and imaginary parts separately, and using them to calculate the modulus squared rapidly.

This code will probably be slightly slower than the complex version without numba (more lines for the interpreter to interpret), and about the same speed with (the compilation step should reduce both versions to very similar sets of instructions, as they do the same thing).