Как нарисовать Мандельброта в Java с помощью SWING / AWT? - PullRequest
1 голос
/ 21 ноября 2019

Я пытаюсь нарисовать набор Мандельброта с точками в наборе как черными, а все остальное - белыми. В этой первоначальной версии я не хочу увеличивать масштаб, а просто создавать статичное изображение.

Я создал класс ComplexNumber, как показано ниже, для обработки возведения в квадрат и сложения комплексных чисел.

public class ComplexNumber {

    private double real;
    private double imaginary;

    public ComplexNumber(double real, double imaginary){
        this.real = real;
        this.imaginary = imaginary;
    }

    public ComplexNumber times(ComplexNumber number){

        double a = this.real*number.real;
        double b = this.imaginary*number.real;
        double c = this.real*number.imaginary;
        double d = this.imaginary*number.imaginary*-1;

        double newReal = a+d;
        double newImaginary = b+c;


        ComplexNumber newComplexNumber = new ComplexNumber(newReal, newImaginary);
        return newComplexNumber;
    }

    public ComplexNumber add(ComplexNumber number){

        double newReal = this.real+number.real;
        double newImaginary = this.imaginary+number.imaginary;

        return new ComplexNumber(newReal, newImaginary);

    }

    public double abs(){
        return Math.hypot(this.real, this.imaginary);
    }

    public double getReal() {
        return real;
    }

    public double getImaginary() {
        return imaginary;
    } 
}

А вот код, в котором я визуализирую графический интерфейс и фактически вычисляю точки внабор Мандельброта.

    import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class MandelBrotSet extends JComponent {

    public static final int WIDTH = 800;
    public static final int HEIGHT = 800;
    public static final int ITERATIONS = 100;

    public static final double startX = -2;
    public static final double width = 4;
    public static final double startY = 2;
    public static final double height = 4;

    public static final double dx = width/(WIDTH-1);
    public static final double dy = height/(HEIGHT-1);

    private BufferedImage buffer;


    public MandelBrotSet() {

        buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

        JFrame frame = new JFrame("Mandelbrot Set");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(true);
        frame.getContentPane().add(this);

        frame.pack();
        frame.setVisible(true);


    }

    @Override
    public void addNotify() {
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
    }

    @Override
    public void paint(Graphics g) {
        g.drawImage(buffer, 0, 0, null);
    }

    public void render(){

        for (int x=0; x<WIDTH; x++){
            for (int y=0; y<HEIGHT; y++){
                int color = calculatePoint(x, y);
                buffer.setRGB(x, y, color);
            }
        }
    }



    public int calculatePoint(int x, int y){

        ComplexNumber number = convertToComplex(x, y);
        ComplexNumber z = number;
        int i;
        for (i=0; i<ITERATIONS; i++){

            z = z.times(z).add(number);

            if (z.abs()>2.0){
                break;
            }

        }

        if (i==ITERATIONS) {
            return 0x00000000;
        }
        else {
            return 0xFFFFFFFF;
        }

    }

    public static ComplexNumber convertToComplex(int x, int y){

        double real = startX + x*dx;
        double imaginary = 2 - y*dy;
        return new ComplexNumber(real, imaginary);

    }




    public static void main(String[] args) {

        MandelBrotSet mandy = new MandelBrotSet();
        mandy.render();

    }


}

После запуска этого кода я получаю изображение ниже. Кажется, есть небольшой проблеск множества Мандельброта, но затем он затенен тонной черного. Что я делаю не так?

enter image description here

Обновленное решение ниже. Спасибо за помощь.

enter image description here

...