import java.awt.*; // Draws the Mandelbrot set. The Mandelbrot set consists of all // values of c for which the following iterative function // // x_i = x_(i-1)^2 + c // // does not grow above 2 for some number of iterations. class Mandelbrot { // The number of iterations to apply the iterative function. // Higher values lead to a more accurate approximation of the // fractal. public static final double ITERATIONS = 100; // The CENTER_X and CENTER_Y constants allow you to translate // the image. public static final double CENTER_X = 0; public static final double CENTER_Y = 0; // Higher values of MARGIN will zoom the image out; smaller // values zoom in. public static final double MARGIN = 2; // Try the following values for a good time: // public static final double CENTER_X = -0.77568377; // public static final double CENTER_Y = 0.13646737; // public static final double MARGIN = 0.001; public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(500, 500); panel.setBackground(Color.WHITE); int width = panel.getWidth(); int height = panel.getHeight(); // The boundaries of the image in the space of the fractal double top = CENTER_Y + MARGIN; double bottom = CENTER_Y - MARGIN; double left = CENTER_X - MARGIN; double right = CENTER_X + MARGIN; Color[][] pixels = panel.getPixels(); for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { // Map the current pixel to a complex number in the // fractal space. double real = map(col, 0, width, left, right); double imaginary = map(row, 0, height, top, bottom); pixels[row][col] = getPixelColor(new Complex(real, imaginary)); } } panel.setPixels(pixels); } // Given a value in the range (istart, istop), returns the value // mapped to the new range (ostart, ostop). public static double map(double value, double istart, double istop, double ostart, double ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } // Given the complex constant c, determines whether the function // // f(x) = x^2 + c // // is bounded after repeated iterations on itself. Returns Color.BLACK // if the function is bounded, or Color.WHITE if the magnitude of x // reaches 2. public static Color getPixelColor(Complex c) { Complex x = new Complex(0, 0); for (int i = 0; i < 100; i++) { x = x.square(); x = x.add(c); } if (x.magnitude() < 2) { return Color.BLACK; } else { return Color.WHITE; } } }