Skip to content

A C# Windows Forms application to view the Mandelbrot Set.

License

Notifications You must be signed in to change notification settings

sds100/MandelbrotSet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

78 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MandelbrotSet

A C# Windows Forms application to view the Mandelbrot Set.

Roadmap

  • Add rulers to the bottom and left side.
  • Export .png image of a user desired portion of the Mandelbrot Set with a custom resolution

Understanding the code

This is mainly for me so if I ever come back to this project, I can understand what my crazy mind was thinking. You can also read it to learn (maybe) about complex numbers and the Mandelbrot Set.

What is a complex number?

A complex number is a number expressed in the form a + bi where a and b are real numbers and i is an "imaginary number". For example 7 + 3i where i could be

The algorithm


Z and C are complex numbers.

For example, where (the first iteration of Z) and C are ...





because...


Therefore...




is then substituted back into the formula.

How do you write the algorithm in code?

The type of variable we choose to store Z and C as massively affects how far we can zoom in before bands start appearing down the screen. This happens because the limits of floating point precision are met. By using BigDecimal (in C#), we can overcome this but it is MUCH slower.

i can be represented by it's coefficient.

    while (z_real * z_real + z_im * z_im < 4 && iteration < MAX_ITERATIONS)
    {
      double z_real_tmp = (z_real * z_real) - (z_im * z_im) + c_real;

      z_im = 2 * z_real * z_im + c_im;
      z_real = z_real_tmp;
    }

(z_real) is calculated from

and

(z_im) is calculated from . because...

The formula in its most basic terms is... which simplifies to...


The real terms are grouped together to calculate . is the same as .
The complex terms are grouped together to calculate . is the same as .

Using a ComplexNumber class

  // Convert the pixel coordinate to the equivalent coordinate on the given portion of the complex plane.
  double c_real = ((pixelCoords.X - bitmapWidth / 2) * planeWidth / bitmapWidth)
      + planeCentre.X;

  double c_im = ((pixelCoords.Y - bitmapHeight / 2) * planeHeight / bitmapWidth)
      + planeCentre.Y;

  var z = new ComplexNumber(0,0);
  var c = new ComplexNumber(c_real, c_im);
            
  int iteration = 0;
  
  while (z.Normal < 4 && iteration < MAX_ITERATIONS)
  {
      z = z * z + c;

      iteration++;
  }

How do you multiply two complex numbers?

For example, If we multiply out these brackets and simplify where i =



And since we know that i is an imaginary number which is is the square-root of a real number.

=
=
=

Therefore...

=
=

There we go!
=