Fractal in C#

Question

Tuesday, October 29, 2013 7:03 PM

Hi,

I found a code on the internet to program a fractal in C#. Can someone explain me how the fractal get's it shape with this code?

The Code

private void Form1_Load(object sender, EventArgs e)
        {
            Bitmap pic = Mandelbrotset(pictureBox1, 2, -2, 2, -2);
            pictureBox1.Image = pic;
        }

        static Bitmap Mandelbrotset(PictureBox pictureBox1, double Xmax, double Xmin, double Ymax, double Ymin)
        {
            pXmax = Xmax;
            pYmax = Ymax;
            pXmin = Xmin;
            pYmin = Ymin;
            Bitmap pic = new Bitmap(pictureBox1.Width, pictureBox1.Height);
           
            double zx = 0;
            double zy = 0;
            double cx = 0;
            double cy = 0;
            double xzoom = ((Xmax - Xmin) / Convert.ToDouble(pic.Width)); 
            double yzoom = ((Ymax - Ymin) / Convert.ToDouble(pic.Height));
            double tempzx = 0;
            
            int loopgo = 0; 
            for (int x = 0; x < pic.Width; x++)
            {
                cx = (xzoom * x) - Math.Abs(Xmin); 
                for (int y = 0; y < pic.Height; y++)
                {
                    zx = 0; 
                    zy = 0;
                    cy = (yzoom * y) - Math.Abs(Ymin); 
                    loopgo = 0; 

                    while (zx * zx + zy * zy <= 4 && loopgo < 1000)
                    {
                        loopgo++; 
                        tempzx = zx;
                        zx = (zx * zx) - (zy * zy) + cx; 
                        zy = (2 * tempzx * zy) + cy;
                    }

                    if (loopgo != 1000)
                        pic.SetPixel(x, y, Color.FromArgb(loopgo % 128 * 2, loopgo % 32 * 7, loopgo % 16 * 14));
                    else
                        pic.SetPixel(x, y, Color.Black);

                }
            }

            return pic;

        }

Hope someone can help.

Thanks!

All replies (1)

Tuesday, October 29, 2013 7:41 PM âś…Answered

Hi, that's the Mandelbrot Set. Plenty of information on wikipedia, but in a nutshell it boils down to this:

Each pixel is mapped to a point in the complex plane. On that complex number (let's call it c), a sequence is computed as follows:

Z(0) = c
Z(n + 1) = Z(n)^2 + c

you keep computing the sequence until it diverges to infinite (actually, you just have to check if its norm gets to 2 or larger), or you give up trying (at 1000 iterations in the code above).

Those points for which the sequence doesn't diverge belong to the Mandelbrot Set and their corresponding pixels get painted black. The other pixels get painted with different colors, depending on how fast the sequence diverged (i.e. how many iterations it took to get to a norm of 4 or larger).

It's worth mentioning that C# now has a Complex data type, which should make writing that code a lot easier.

HTH
--mc