I am currently trying to code a program which generates a mandelbrot-set. however even though i did a lot of testing with each single method. The shape of the whole set seems to be wrong .I am looking for help and would be really glad if someone knows how to fix it.
import java.awt.*;
import javax.swing.*;
public class MandelbrotMenge extends JComponent {
int WIDTH = 600;
int HEIGHT = 600;
static int n = 1; // anzahl iterationen
static double a; // reeller Anteil von komplexer Zahl
static double b; // imaginärer Anteil
public MandelbrotMenge(int p_n) {
setSize(WIDTH, HEIGHT);
n = p_n;
}
public static boolean isMandelbrot(double a_n, double b_n, int n) { // prüft
// ob
// komplexe
// zahl
// divergiert
a = a_n;
b = b_n;
double a2 ;
for (int i = 0; i < n; i++) {
a2 = a * a - b * b + a;
b = 2 * a * b + b;
a=a2;
if (a * a + b * b >= 4)
return false;
}
return true;
}
public static void zeichneMandelbrot(Graphics g,int n) {
for (int i = 100; i <= 600; i++) {
for (int j = 0; j <= 600; j++) {
// i ist pixel und j auch
// komplexe zahl:
a = -3 + 0.01 * i; // x min = -3 x max = 6 pixel =600 --> 0.01*i
b = 3 - 0.01 * j;
if (isMandelbrot(a, b, n)) {
g.setColor(Color.white);
} else {
g.setColor(Color.black);
}
g.drawLine(i, j, i, j);
}
}
}
protected void paintComponent(Graphics g) {
zeichneMandelbrot(g, n);
}
}
The shape looks (not completely) wrong:
Mathematically speaking, you are iterating the specific function f(z)=z^2+z
from a 500 by 500 pixel grid of initial values and what you have generated is exactly the Julia set of that function. To generate the Mandelbrot set, you need to iterate f(z)=z^2+c
, but now, you always use the same initial point 0 while you let the parameter c
range throughout a grid.
Thus, instead of
a = a_n;
b = b_n;
double a2 ;
for (int i = 0; i < n; i++) {
a2 = a * a - b * b + a;
b = 2 * a * b + b;
a=a2;
...
}
You'd need something like
z_a = 0;
z_b = 0;
a = c_a
b = c_b
double z_a2 ;
for (int i = 0; i < n; i++) {
a2 = z_a * z_a - z_b * z_b + a;
b = 2 * z_a * z_b + b;
a=a2;
...
}
In this code, z_a
and z_b
represent the real and imaginary parts of the complex variable z
while c_a
and c_b
represent the real and imaginary parts of the complex parameter c
. The iteration always starts from zero, which is why z_a
and z_b
are both set to zero at the outset. The parameter c
changes, though.