mandelbrot confusion

I’m trying to apply the mandelbrot set to my shader, but I’ve encountered a road block. first of all, osl doesn’t seem to support complex numbers. you can’t use pow(-1, 0.5) for example. I found a script that someone else wrote that seems to work, but I can’t figure out why, and if I don’t understand it, I can’t manipulate it. here’s is the code that works:

shader Fractal(
    float Hue = 0,
    point pos = P,
    output color Color = 0
){
    int i;
    float real = pos[0];
    float imag = pos[1];
    float x = real;
    float y = imag;
    real = 0;
    imag = 0;
    for(i = 0; i < 20; i++) {
        float realt = pow(real,2) - pow(imag, 2) + x;
        imag = 2*imag*real + y;
        real = realt;
        if(pow(real,2)+pow(imag,2)>4){
          Color = color("hsv", Hue, 1, i/20.0);
          break;
        }
    } 
}

looking at this code I see no complex numbers. it doesn’t have anything in the form y = z^2 + c.

I just found some insight into the way the code works from the mandelbrot wikipedia page:

In pseudocode, this algorithm would look as follows. The algorithm does not use complex numbers and manually simulates complex-number operations using two real numbers, for those who do not have a complex data type. The program may be simplified if the programming language includes complex-data-type operations.

For each pixel (Px, Py) on the screen, do:
{
x0 = scaled x coordinate of pixel (scaled to lie in the Mandelbrot X scale (-2.5, 1))
y0 = scaled y coordinate of pixel (scaled to lie in the Mandelbrot Y scale (-1, 1))
x = 0.0
y = 0.0
iteration = 0
max_iteration = 1000
while (xx + yy < 22 AND iteration < max_iteration) {
xtemp = x
x - yy + x0
y = 2
x*y + y0
x = xtemp
iteration = iteration + 1
}
color = palette[iteration]
plot(Px, Py, color)
}

the script on my above post is clearly derived from this pseudo code. now I just need to figure out how to make a similar script but with julia sets.

I’ll try to help, but i’m not really a math expert:

The fractal can be mapped directly into the imaginary and real axis, as y(im) and x(real),

What do we have from the formula:
z = x + iy
zz = xx + i2xy - y*y
c = x0 + y0

So we have to put it all in the right context, note that the x is the real axis so i dont want imaginary parts in there:

x= xx - yy + x0 - note that i added the zz without the imaginary number and the x0 that belongs to x
y = 2xy + y0 - note that the y is the imaginary axis so i will add the imaginary number from z
z and the y0

That’s why you’ll get a code like this:
xtemp = xx - yy + x0
y = 2xy + y0

Now, this will be calculated 1000 for each pixel of your image, since it will take it’s original position into consideration it will apply the formula until the pixel coordinates reach the boundary of the fractal, it’s final destination,

I hope it helped a bit