Skip to content

Instantly share code, notes, and snippets.

@higuoxing
Created November 7, 2019 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save higuoxing/db4d27e387f9099516391dd99bd4261c to your computer and use it in GitHub Desktop.
Save higuoxing/db4d27e387f9099516391dd99bd4261c to your computer and use it in GitHub Desktop.
C code for generating mandelbrot set.
#include <stdio.h>
#include <math.h>
#define PPM_FILE_NAME "mandelbrot.ppm"
#define COMMENT "# This is an image on mandelbrot set"
#define IMAGE_WIDTH 800
#define IMAGE_HEIGHT 800
#define MAX_COLOR_VALUE 255
#define CX_MIN (-2.5 - 0.5) / 1.9
#define CX_MAX (1.5 - 0.5) / 1.9
#define CY_MIN -2.0 / 1.9
#define CY_MAX 2.0 / 1.9
#define PIXEL_WIDTH (CX_MAX - CX_MIN) / IMAGE_WIDTH
#define PIXEL_HEIGHT (CY_MAX - CY_MIN) / IMAGE_HEIGHT
#define ITERATION_TIMES 200
#define ESCAPE_CIRCLE 2 * 2
FILE *file;
static unsigned char pixel[3];
void init_ppm_image() {
file = fopen(PPM_FILE_NAME, "wb" /* Binary Mode */);
// Write file headers.
fprintf(file,
"P6\n"
" %s\n" /* Comments */
" %d\n %d\n" /* File Size */
" %d\n" /* 0-255 */,
COMMENT, IMAGE_WIDTH, IMAGE_HEIGHT, MAX_COLOR_VALUE);
}
int main() {
init_ppm_image();
// Z = Zx + i * Zy
double Zx, Zy;
double Cx, Cy;
// Iterate over every pixel.
for (int y = 0; y < IMAGE_HEIGHT; ++ y) {
Cy = CY_MIN + y * PIXEL_HEIGHT;
if (fabs(Cy) < PIXEL_HEIGHT / 2) {
Cy = 0.0;
}
for (int x = 0; x < IMAGE_WIDTH; ++ x) {
Cx = CX_MIN + x * PIXEL_WIDTH;
Zx = 0.0;
Zy = 0.0;
int iter;
for (iter = 0; iter < ITERATION_TIMES &&
Zx * Zx + Zy * Zy < ESCAPE_CIRCLE; ++ iter) {
double Zxx = Zx;
double Zyy = Zy;
// Z(n) = Z(n - 1) ^ 2 + C
// Z_x(n) = Z_x(n - 1) ^ 2 - Z_y(n - 1) ^ 2 + C_x
Zx = Zxx * Zxx - Zyy * Zyy + Cx;
// Z_y(n) = 2 * Z_x(n - 1) * Z_y(n - 1) + C_y
Zy = 2 * Zxx * Zyy + Cy;
}
if (iter == ITERATION_TIMES) {
pixel[0] = 0;
pixel[1] = 0;
pixel[2] = 0;
} else {
pixel[0] = 255;
pixel[1] = 255;
pixel[2] = 255;
}
fwrite(pixel, 1, 3, file);
}
}
fclose(file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment