三、曼德勃羅集合(Mandelbrot Set)
曼德勃羅集合(Mandelbrot Set)或曼德勃羅復數集合,是一種在復平面上組成分形的點的集合,因由曼德勃羅提出而得名。曼德博集合可以使復二次多項式 進行迭代來獲得。其中,c是一個復參數。對於每一個c,從 z = 0 開始對fc(z)進行迭代。序列
的值或者延伸到無限大,或者只停留在有限半徑的圓盤內(這與不同的參數c有關)。曼德布洛特集合就是使以上序列不延伸至無限大的所有c點的集合。
最后,我們給出一個利用C語言生成Mandelbrot集合並繪制圖形的程序(該程序來自文獻【1】):
#include <stdio.h> #include <stdlib.h> #include <complex.h> #define width_size 800 #define height_size 600 #define Maxval 255 static const float orig_x = width_size * 2/3; static const float orig_y = height_size * 1/2; static const pixel dim_gray = { 105, 105, 105 };
typedef struct _pixel { unsigned char r; unsigned char g; unsigned char b; } pixel;static unsigned char iteration(int x, int y) { const int limit = Maxval + 1; int i; complex c = ((x - orig_x) / (width_size / 3)) + ((orig_y - y) / (height_size / 2)) * I; complex z = 0; for (i = 0; i < limit; i++) { /* basic formula */ z = z * z + c; if (creal(z) > 2 || cimag(z) > 2) break; } return (unsigned char) (i == limit ? 0 : i); } int main() { FILE *f = fopen("mandelbrot.ppm", "w+"); /* PPM header */ fprintf(f, "P6\n" /* PPM magic number */ "#Mandelbrot Set\n" "%d " /* width, in ASCII decimal */ "%d\n" /* height, in ASCII decimal */ "%d\n", /* maximum color value, in ASCII decimal */ width_size, height_size, Maxval); /* Write every pixel generated by Mandelbrot Set */ for (int i = 0; i < height_size; i++) { for (int j = 0; j < width_size; j++) { unsigned char iter = iteration(j, i); if (iter) { pixel p = { .r = iter, .g = (float) abs(j - orig_x) / width_size * Maxval, .b = (float) abs(i - orig_y) / height_size * Maxval }; fwrite(&p, sizeof(pixel), 1, f); } else { fwrite(&dim_gray, sizeof(pixel), 1, f); } } } fclose(f); return 0; }
上述程序所生成的圖像結果如下圖所示,需要補充說明的是:該圖像文件格式為ppm,在Windows下你可以使用Photoshop來查看這種類型的圖像文件,在OS X系統下你可以使用免費的GIMP軟件來查看它。
參考 http://blog.linux.org.tw/~jserv/archives/2011/09/_mandelbrot_set.html