Search code examples
c#fractalsmandelbrot

mandlebrot fractal error in the plotted function


Hello guys i am trying plotting the mandlebrot fractal but the result is very far from it, can you help me to find the why?

Here is the code:

void Button1Click(object sender, EventArgs e)
{
    Graphics g = pbx.CreateGraphics();
    Pen p = new Pen(Color.Black);

    double xmin = -2.0;
    double ymin = -1.2;
    double xmax = 0;
    double ymax = 0;
    double x = xmin, y = ymin;
    int MAX = 1000;

    double stepY = Math.Abs(ymin - ymax)/(pbx.Height);
    double stepX = Math.Abs(xmin - xmax)/(pbx.Width);

    for(int i = 0; i < pbx.Width; i++)
    {
        y = ymin;
        for(int j = 0; j < pbx.Height; j++)
        {
            double rez = x;
            double imz = y;
            int iter = 0;

            while(rez * rez + imz * imz <= 4 && iter < MAX)
            {
                rez = rez * rez - imz * imz + x;
                imz = 2 * rez * imz + y;
                iter++;
            }
            if(iter == MAX)
            {
                p.Color = Color.Black;
                g.DrawRectangle(p, i, j, 1, 1);
            }
            else
            {
                p.Color = Color.White;
                g.DrawRectangle(p, i, j, 1, 1);
            }
            y += stepY;
        }
        x += stepX;
    }
}

please help me my mind is getting crushed thinking how to get the beautiful mandlebrot set... and sorry if i committed some mistakes but English is not my speaked language!


Solution

  • You have some irregularities elsewhere. The range you're plotting isn't the entire set, and I would calculate x and y directly for each pixel, rather than using increments (so as to avoid rounding error accumulating).

    But it looks to me as though your main error is in the iterative computation. You are modifying the rez variable before you use it in the computation of the new imz value. Your loop should look more like this:

    while(rez * rez + imz * imz <= 4 && iter < MAX)
    {
        double rT = rez * rez - imz * imz + x;
    
        imz = 2 * rez * imz + y;
        rez = rT;
        iter++;
     }