Skip to content

Instantly share code, notes, and snippets.

@PurpleMyst
Last active August 6, 2017 02:48
Show Gist options
  • Save PurpleMyst/75b686278334f63169bca10a955b7b77 to your computer and use it in GitHub Desktop.
Save PurpleMyst/75b686278334f63169bca10a955b7b77 to your computer and use it in GitHub Desktop.
Simple grayscale mandelbrot set visualization outputted in PGM format.
#include <stdio.h>
#include <stdint.h>
#include <complex.h>
#define MAX_ITERATIONS 80
#define REAL_START -2
#define REAL_END 1
#define IMAG_START -1
#define IMAG_END 1
#define IMAGE_WIDTH 1920
#define IMAGE_HEIGHT 1080
static uint_fast8_t iterations(const double x, const double y) {
uint_fast8_t n = 0;
double complex c = (REAL_START + (x / IMAGE_WIDTH) * (REAL_END - REAL_START)) +
(IMAG_START + (y / IMAGE_HEIGHT) * (IMAG_END - IMAG_START)) * I;
for (double complex z = 0; cabs(z) <= 2 && n < MAX_ITERATIONS; z = z * z + c, ++n);
return n;
}
int main(void) {
printf("P2\n");
printf("%d %d\n", IMAGE_WIDTH, IMAGE_HEIGHT);
printf("255\n");
for (double y = 0; y < IMAGE_HEIGHT; ++y) {
for (double x = 0; x < IMAGE_WIDTH; ++x) {
const uint_fast8_t n = iterations(x, y);
const uint_fast8_t color = 255 - (n * 255 / MAX_ITERATIONS);
if (x > 0) printf(" ");
printf("%d", color);
}
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment