我被要求在Java上显示Mandelbrot,但我遇到了一个问题。我的老师和我都难以理解为什么这不能正常运行。
我认为它与算法或复杂类有关,因为除了正/负1和0之外的所有值在两次迭代后都会转移到无穷大。
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);
}
}
}
}
答案 0 :(得分:3)
我认为你必须有广泛的界限。 [-200,100],你应该有[-2,1]代表Re和[-1,1]代表Im。
complex C = new complex(x/SCALE,y/SCALE);
答案 1 :(得分:0)
complex C = new complex(x/SCALE,y/SCALE); // math done on unscaled values
由于x
和y
都是int
s(以及SCALE
),所以你在这里进行整数除法。
请改为尝试:
complex C = new complex((double)x/SCALE,(double)y/SCALE); // math done on unscaled values
顺便说一下,这不是错误,但add()
和multiply()
应该是Complex
类的方法,应该根据Java命名约定大写。< / p>