Mandelbrot.java


Below is the syntax highlighted version of Mandelbrot.java from §3.2 Creating Data Types.

/*************************************************************************
 *  Compilation:  javac Mandelbrot.java
 *  Execution:    java Mandelbrot x y w h                            
 *  Dependencies: Picture.java
 *  
 *  Plots the w-by-h region of the Mandelbrot set with lower left
 *  endpoint (x, y) in grayscale.   
 *
 *  % java Mandelbrot -1.5 -1 2 2
 *
 *  % java Mandelbrot .10259 -.641 .0086 .0086
 *
 *  Bug: upper left of Picture is (0, 0)
 *
 *************************************************************************/
import java.awt.Color;

public class Mandelbrot {

    // return number of iterations to check if c = a + ib is in the Mandelbrot set
    public static int mand(Complex c, int ITERS) {
        Complex z = c;
        for (int t = 0; t < ITERS; t++) {
            if (z.abs() >= 2.0) return t;
            z = z.times(z).plus(c);
        }  
        return ITERS - 1;
    }


    public static void main(String args[]) {
        double xmin   = Double.parseDouble(args[0]);      // min x coordinate
        double ymin   = Double.parseDouble(args[1]);      // min y coordinate
        double width  = Double.parseDouble(args[2]);      // width of plot
        double height = Double.parseDouble(args[3]);      // height of plot

        int WIDTH  = 250;
        int HEIGHT = 250;
        int ITERS  = 256;

        Picture pic = new Picture(WIDTH, HEIGHT);

        for (int i = 0; i < WIDTH; i++) {
            for (int j = 0; j < HEIGHT; j++) {
                double a = xmin + i * width / WIDTH;
                double b = ymin + height - (j * height / HEIGHT);
                Complex c = new Complex(a, b);
                int gray = ITERS - 1 - mand(c, ITERS);
                Color color = new Color(gray, gray, gray);
                pic.setColor(i, j, color);
            }
        }
        pic.show();
    }

}


Last updated: Sun Oct 17 22:20:06 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.