【问题标题】:Clojure/Java Mandelbrot Fractal drawingClojure/Java Mandelbrot 分形绘图
【发布时间】:2009-07-10 21:58:44
【问题描述】:

我正在尝试将此 algorithm 移植到 clojure。

我的代码是

(defn calc-iterations [x y] 
  (let [c (struct complex x y)]
    (loop [z (struct complex 0 0) 
           iterations 0]
      (if (and (< 2.0 (abs z))
               (> max-iterations iterations))
        iterations
        (recur (add c (multiply z z)) (inc iterations))))))

乘法、加法和 abs 函数可以正常工作。我用计算器测试过它们。但是对于以下值:

(calc-iterations 0.60703135 -0.33984375) ; should give me 2, instead I get 4
(calc-iterations -1.8421874 0.3515625 )  ; should give me 1, instead I get 3

我正在使用我在网上找到的另一个 java 小程序检查正确的迭代次数。它似乎正在工作,因为它产生了正确的输出。它的迭代函数是

protected int calcIterations( float x, float y ) {
    int iterations = 0;

    float xn = x, yn = y;

    while ( iterations < MAX_ITERATIONS ) {
        float xn1 = xn*xn - yn*yn;
        float yn1 = 2*xn*yn;

        xn = xn1 + x;
        yn = yn1 + y;

        float magsq = xn*xn + yn*yn;

        if ( magsq > 4 )
            break;

        iterations++;
    }

    System.out.println( x + " " + y + " " + iterations );
    return iterations;
}

谁能发现我的错误?

【问题讨论】:

    标签: java lisp clojure mandelbrot


    【解决方案1】:

    我发现了两个差异

    1. Java 实现从 z = (x, y) 开始,而不是您的从 (0, 0) 开始。由于您的递归公式是 z = z^2 + c, (0, 0)^2 + (x, y) = (x, y) 所以从 (x, y) 开始与第一次迭代相同。因此,迭代次数将因此比您的少一。
    2. Java 实现增加迭代次数检查结果 z 是否在距离原点 2 个单位以内,否则不增加它,而你的每次都增加迭代。因此,迭代次数也会比你的少一。

    所以这可能是您结果差异的原因。

    我认为你的实现更正确,因为它区分了 |z| 的情况。一次迭代后 > 2(即 |(x,y)| > 2),而 |z| > 2 在两次迭代后(即其中 |(x^2-y^2+x, 2xy+y)| > 2),而 Java 实现将执行其第一次迭代,给出 (x^2-y^2+x , 2xy+y),并在增加迭代次数之前退出,因此不区分这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多