2011-10-20 61 views
6

我試圖在C中實現Mandelbrot集,但我有一個奇怪的問題。我的代碼如下:我的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

感謝您的幫助!

+0

檢查你的邏輯對這個僞代碼:http://en.wikipedia.org/wiki/Mandelbrot_set#For_programmers – Blender

+0

我不知道這是否相關,但我得到'警告:未使用的變量'真正'當我編譯你的代碼。 –

+0

我正在試驗不同的技術來表示真實和虛擬的數字,並忘記刪除它。 –

回答

3

嘗試設置cimax至-0.127,我也是在做這個項目,它似乎做的伎倆;)

2

該代碼看起來不錯。 但是你的起始矩形看起來不正確!

您使用

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

你確定這是你打算怎麼辦?這對我來說似乎是一個非常驚人的規模。

此外,標準曼德爾布羅算法傾向於使用

magnitude > 2 

,而不是50 爲逃避檢查。儘管這不應該影響套件的實際形狀。

+0

修好了!將規模改變爲-127這樣的東西給了我想要的東西。哦,那真是一個愚蠢的錯誤。 –

0

BTW,有一個在計算Z *連詞(z)的平方根是沒有意義的。簡單地將不平等的兩邊的表達式平方,給予if (z*conj(z) > 2500),並且提高了表現。