-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMandelbrot.java
More file actions
82 lines (66 loc) · 2.31 KB
/
Mandelbrot.java
File metadata and controls
82 lines (66 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Mandelbrot set implementation. Will draw every pixel so takes some time to compute.
*/
public class Mandelbrot {
private static final int WIDTH = 960;
private static final int HEIGHT = 540;
// Max iterations per pixel
private static final int MAX_ITER = 500;
// Bounds in the complex plane
private static final double X_MIN = -2.5;
private static final double X_MAX = 1.0;
private static final double Y_MIN = -1.0;
private static final double Y_MAX = 1.0;
/** Map a pixel coordinate to the real axis */
private static double mapX(int px) {
return X_MIN + px * (X_MAX - X_MIN) / WIDTH;
}
/** Map a pixel coordinate to the imaginary axis */
private static double mapY(int py) {
return Y_MIN + py * (Y_MAX - Y_MIN) / HEIGHT;
}
/** Compute the Mandelbrot iteration count for c = (cr, ci) */
private static int mandelbrotIterations(double cr, double ci) {
double zr = 0;
double zi = 0;
int count = 0;
while (count < MAX_ITER) {
// z^2 = (zr + i zi)^2 = zr^2 - zi^2 + 2 zr zi i
double zr2 = zr * zr - zi * zi;
double zi2 = 2 * zr * zi;
zr = zr2 + cr;
zi = zi2 + ci;
// If magnitude escapes
if (zr * zr + zi * zi > 4.0)
break;
count++;
}
return count;
}
/** Simple coloring: black if inside, gradient if outside */
private static void setColor(int iter) {
if (iter == MAX_ITER) {
StdDraw.setPenColor(0, 0, 0); // black (inside)
} else {
// Smooth gradient (blue-ish)
int val = 255 * iter / MAX_ITER;
StdDraw.setPenColor(0, val, 255 - val);
}
}
public static void main(String[] args) {
StdDraw.setTitle("Mandelbrot Set");
StdDraw.setCanvasSize(WIDTH, HEIGHT);
StdDraw.setXscale(0, WIDTH);
StdDraw.setYscale(0, HEIGHT);
// Draw each pixel
for (int px = 0; px < WIDTH; px++) {
for (int py = 0; py < HEIGHT; py++) {
double cr = mapX(px);
double ci = mapY(py);
int iter = mandelbrotIterations(cr, ci);
setColor(iter);
StdDraw.point(px, py);
}
}
}
}