我的Mandelbrot设置代码出了什么问题?

时间:2011-10-20 00:28:40

标签: c mandelbrot

我正在尝试用C语言实现Mandelbrot,但我遇到了一个奇怪的问题。我的代码如下:

#include <stdio.h>
#include <math.h>
#include <complex.h>

int iterate_pt(complex c);

int main() {
FILE *fp;
fp = fopen("mand.ppm", "w+");


double crmin = -.75;
double crmax = -.74;
double cimin = -.138;
double cimax = -.75; //Changing this value to -.127 fixed my problem.

int ncols = 256;
int nrows = 256;
int mand[ncols][nrows];
int x, y, color;
double complex c;

double dx = (crmax-crmin)/ncols;
double dy = (cimax-cimin)/nrows;

for (x = 0; x < ncols; x++){
    for (y = 0; y < nrows; y++){
        double complex imaginary = 0+1.0i;
        c = crmin+(x*dx) + (cimin+(y*dy)) * imaginary;
        mand[x][y] = iterate_pt(c);
    }
}

printf("Printing ppm header.");
fprintf(fp, "P3\n");
fprintf(fp, "%d %d\n255\n\n", ncols, nrows);

for (x = 0; x < ncols; x++) {
    for (y = 0; y < nrows; y++){
        color = mand[x][y];
        fprintf(fp, "%d\n", color);
        fprintf(fp, "%d\n", color);
        fprintf(fp, "%d\n\n", color); //Extra new line added, telling the ppm to go to next pixel.
    }
}
fclose(fp);

return 0;
}

int iterate_pt(double complex c){
double complex z = 0+0.0i;
int iterations = 0;
int k;
for (k = 1; k <= 255; k++) {
    z = z*z + c;
    if (sqrt( z*conj(z) ) > 50){
        break;
    }
    else
        ++iterations;
}
return iterations;
}

但是,此程序的输出(存储为ppm文件)如下所示:

Converted to a GIF using GIMP. I can confirm that the GIF and original PPM look exactly the same as a PPM and GIF

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

尝试将cimax设置为-0.127,我也正在研究这个项目,它似乎可以解决问题;)

答案 1 :(得分:2)

代码看起来不错。 但你的起始矩形看起来不正确!

您正在使用

Real ranage [  -.75 ,  -.74 ]
Imag range  [ -.138 ,  -.75 ]
你知道这是你的意图吗?对我来说,这似乎是一个非常紧张的y尺度。

此外,标准的mandelbrot算法倾向于使用

magnitude > 2
而不是50。 作为逃生检查。虽然这不应该影响集合的实际形状。

答案 2 :(得分:0)

顺便说一下,计算z * conj(z)的sqrt是没有意义的。简单地对不等式两边的表达式进行平方,给出if (z*conj(z) > 2500)并提高性能。