Mandelbrot Set


 

 

This GUI program simulates the basic Complex Plane using the JPanel and JFrame classes and then constructs the famous Mandelbrot Set on top of it. Each pixel on the drawing surface is programmed to represent a particular complex number. These numbers are then processed one by one using the static method mandelTest() to determine their membership status within the Mandelbrot Set. If they are found to be members, the paintComponent() method will simply color the corresponding pixel black. If they fail the test, then mandelTest() will determine the extent of this failure (the escape rate) and send this information back to PaintComponent(). The pixel will be rendered with a different color based on this information.

Complete Source Code

import java.awt.*;
import javax.swing.*;


public class Mandelbrot {


   public static int mandelTest(int x, int y) {

      double realC, imagC, x0, temp, y0, modulus;

      realC = (double) x/280;
      imagC = (double) -y/280;
      x0 = 0;
      y0 = 0;
      modulus = 0;

      for (int i = 1; i <= 500; i++) {

         temp = x0*x0 - y0*y0 + realC;
         y0 = 2*x0*y0 + imagC;
         x0 = temp;
         modulus = Math.sqrt(x0*x0 + y0*y0);

         if (modulus > 2 && i <= 3) return 6;
         if (modulus > 2 && i > 3 && i <= 5) return 5;
         if (modulus > 2 && i > 5 && i <= 10) return 4;
         if (modulus > 2 && i > 10 && i <= 20) return 3;
         if (modulus > 2 && i > 20 && i <= 40) return 2;
         if (modulus > 2 && i > 40) return 1;

      }

      return 0;

   }

   public static class MSet extends JPanel {

      int testResult;
      Color[] color = {Color.BLACK, Color.CYAN, Color.WHITE,
      Color.YELLOW, Color.ORANGE, Color.RED}

      public void paintComponent(Graphics g) {

         super.paintComponent(g);
         g.translate(642,331);

         for (int x = -642; x <= 242; x++) {

            for (int y = -331; y <= 331; y++) {

               testResult = mandelTest(x,y);

               for (int i = 0; i < 6; i++) {

                  if (testResult == i) {

                     g.setColor(color[i]);
                     g.drawLine(x,y,x,y);

                  }

               }

            }

         }

      }

   }

   public static void main(String[] args) {

      MSet myPanel = new MSet();
      myPanel.setBackground(Color.BLUE);

      JFrame window = new JFrame("Dilip's Mandelbrot Set");
      window.add(myPanel);
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      window.setSize(900,700);
      window.setLocation(100,100);
      window.setVisible(true);

   }


}