Mandelbrot 集的视觉表示

我想使用 Java 生成 Mandelbrot 集的 PNG 照片,输出应该很容易在谷歌图像搜索中找到。


该集合定义为以下序列:


z_n+1 = z_n^2 + c

其中c和z是复数,并且z始终具有小于 2 的模数。


我首先为复数定义了一个类,其中还包含所需的基本复杂运算。


public class ComplexNumber {

    private double real;

    private double imaginary;


    public ComplexNumber(double real, double imaginary) {

        this.real = real;

        this.imaginary = imaginary;

    }


    public ComplexNumber add(ComplexNumber z1, ComplexNumber z2) {

        ComplexNumber sum = new ComplexNumber(0, 0);

        sum.real = z1.real + z2.real;

        sum.imaginary = z1.imaginary + z2.imaginary;

        return sum;

    }


    public ComplexNumber square(ComplexNumber z) {

        ComplexNumber squared = new ComplexNumber(0, 0);

        squared.real = Math.pow(z.real, 2) - Math.pow(z.imaginary, 2);

        squared.imaginary = 2 * z.real * z.imaginary;

        return squared;

    }


    public double abs() {

        double absolute = Math.sqrt(Math.pow(this.real, 2) + Math.pow(this.imaginary, 2));

        return absolute;

    }

}

然后我定义了 Mandelbrot 类,它获取许多复数 c(基于像素)检查这些数字是否在使用 mandelbrot 方法的 mandelbrot 集中,并将此方法的输出转换为要显示的颜色。


import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;


import javax.imageio.ImageIO;


public class Mandelbrot {


    public static int mandelbrot(ComplexNumber c, ComplexNumber z, int i, int n) {

        if (i < n) {

            if (c.abs() > 2.0) {

                return i;

            } else

                return 0;

        }

        return mandelbrot(c, z.square(z).add(z, c), i, n);

    }

白板的微信
浏览 116回答 1
1回答

慕标琳琳

看起来您的递归 mandelbrot 函数的终止条件不正确。您希望 mandelbrot 函数返回,当z 的绝对值超过 2 或达到最大递归深度。另外,你永远不会增加 i。所以更新后的函数看起来像:public static int mandelbrot(ComplexNumber c, ComplexNumber z, int i, int n) {&nbsp; &nbsp; if (i >= n) {&nbsp; &nbsp; &nbsp; &nbsp; // mandelbrot function does not diverge after n iterations.&nbsp; &nbsp; &nbsp; &nbsp; // Returning -1 as a magic value to indicate that the point c is in the mandelbrot set.&nbsp; &nbsp; &nbsp; &nbsp; // Values may already be outside of the mandelbrot set in the 0th iteration, so returning -1 makes more sense.&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; } else if (z.abs() >= 2.0) {&nbsp; &nbsp; &nbsp; &nbsp; // mandelbrot function is diverging after i iterations.&nbsp; &nbsp; &nbsp; &nbsp; return i;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // recursively call mandelbrot function with an updated z and an incremented i.&nbsp; &nbsp; &nbsp; &nbsp; return mandelbrot(c, z.squared().add(c), i + 1, n);&nbsp; &nbsp; }}最后,如果您选择为 mandelbrot 集中的某个点返回 -1,则必须更新您的颜色计算以将这些点设置为黑色。int mb = mandelbrot(c, z0, 0, maxRecurse);if (mb == -1) {&nbsp; &nbsp; image.setRGB(x, y, 0);} else {&nbsp; &nbsp; // set the color of your image as usual}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java