Rest in peace Mandelbrot

on 16 Oct 2010 by Mukund (@muks)

Rest in peace, Mandelbrot. A long time ago, what you created caught my eye, and made me love computer graphics.

Mandelbrot Set 1 Mandelbrot Set 2

/* This code was placed in the public-domain by Mukund Sivaraman on
   October 16, 2010. Do whatever you want with it. */

#include <stdio.h>
#include <math.h>

/* Boundaries of the set */

#define X1 -2.0
#define X2  1.0
#define Y1 -1.2
#define Y2  1.0

/* Dimensions of the output PPM in pixels */

#define WIDTH  4290
#define HEIGHT 2856

int
main (int argc, char *argv[])
{
  FILE *out;
  int i, j, k;

  double x1 = X1;
  double x2 = X2;
  double y1 = Y1;
  double y2 = Y2;

  double cx, cy, zx, zy, tx;
  double dx, dy;

  int sines[256];

  if (argc != 2)
    {
      fprintf (stderr, "Usage: %s <output-ppm-file>\n", argv[0]);
      return 1;
    }

  out = fopen (argv[1], "wb");
  if (!out)
    {
      fprintf (stderr, "Unable to open output file: %s\n", argv[1]);
      return 1;
    }

  for (i = 0; i < 256; i++)
    {
      double a = M_PI * 2 * i / 256;
      sines[i] = (int) fabs (sin (a) * 255);
    }

  fprintf (out, "P6\n%d %d\n255\n", WIDTH, HEIGHT);

  dx = x2 - x1;
  dy = y2 - y1;

  for (j = 0; j < HEIGHT; j++)
    {
      cy = y1 + ((j / (HEIGHT * 1.0)) * dy);

      for (i = 0; i < WIDTH; i++)
        {
          cx = x1 + ((i / (WIDTH * 1.0)) * dx);

          zx = cx;
          zy = cy;

          for (k = 0; k < 255; k++)
            {
              if (((zx * zx) + (zy * zy)) >= 4.0)
                break;

              tx = cx + ((zx * zx) - (zy * zy));
              zy = cy + (2 * zx * zy);
              zx = tx;
            }

          fprintf (out, "%c%c%c", sines[k], sines[k], sines[k]);
        }
    }

  fclose (out);

  return 0;
}

Download mandelbrot.c.