6

我正在尝试在 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 文件的该程序的输出如下所示:

使用 GIMP 转换为 GIF。 我可以确认 GIF 和原始 PPM 看起来与 PPM 和 GIF 完全相同

谢谢你的帮助!

4

3 回答 3

3

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

于 2011-10-20T00:54:37.953 回答
2

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

您正在使用

Real ranage [  -.75 ,  -.74 ]
Imag range  [ -.138 ,  -.75 ]

你确定这是你想要的吗?对我来说,这似乎是一个非常拉伸的 y 尺度。

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

magnitude > 2

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

于 2011-10-20T00:48:13.507 回答
0

顺便说一句,计算 z*conj(z) 的 sqrt 没有意义。只需将不等式两边的表达式平方,给予if (z*conj(z) > 2500),你就提高了表现。

于 2011-10-28T11:19:23.237 回答