我正在尝试用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](https://istack.dev59.com/iNLaP.gif)
if (sqrt( z*conj(z) ) > 50){
。如果你想要获取幅值,可以使用cabs(z)
。 - Tom Zychsqrt(z * conj(z))
就是幅度,如果我花十秒钟想一想就会意识到这一点。真正的改进应该是跳过sqrt
并将其与2500进行比较。 - Tom Zych