I was asked to display the Mandelbrot set on Java but I have encountered a problem. My teacher and I both are stumped to why this doesn't run correctly.
I reckon it has something to do with the algorithm or the complex class since all values except positive/negative 1 and 0 escape to infinity after two iterations.
import javax.swing.*;
import java.awt.*;
public class fractal {
public class complex { double re; double im;
public complex(double x, double y){
this.re =x;
this.im =y;
}
public double mag(){
return (Math.sqrt(re*re+im*im));
}
}
static int xcord = 500;
static int ycord = 500;
public static void main(String[] args) {
JFrame myFrame = new JFrame("Question 10");
myFrame.setSize(xcord,ycord);
JPanel myPane = (JPanel) myFrame.getContentPane();
myPane.add(new paint());
myFrame.setVisible(true);
}
}
class paint extends JComponent {
public complex add(complex a, complex b){
return new complex(a.re+b.re,a.im+b.im);
}
public complex multiply(complex a,complex b) {
return new complex((a.re*b.re)-(a.im*b.im),(a.re*b.im)+(a.im*b.re));
}
public void paint (Graphics g){
final int SCALE =100; //pixels per unit
int itr = 0;
int max_itr = 30;
Color clr = Color.black;
g.translate(fractal.xcord/2, fractal.ycord/2); // Move origin to center of frame
for (int x = -2*SCALE; x <= 1*SCALE; x++){
for (int y = -1*SCALE; y <= 1*SCALE; y++){
complex C = new complex(x/SCALE,y/SCALE); // math done on unscaled values
complex z = C;
itr = 0;
while ( z.mag() <= 4.0 && itr < max_itr){
z = add(multiply(z,z),C);
itr++;
}
if (itr == max_itr){
clr = Color.black;
}
else{
clr = new Color((int) Math.round(itr*8.5),(int) Math.round(itr*8.5),(int) Math.round(itr*8.5)); // Colouring of fractal
}
g.drawOval(x, y, 2, 2);
g.setColor(clr);
}
}
}
}
I think that you have to wide boundaries. [-200,100], where you should have [-2,1] for Re and [-1,1] for Im.