Simple Mandelbrot set generator

The orginal Graphics Without Greek notes were written back in the late '80s or very early '90s. I recently (October of 2011) discovered that this page was missing from my web archive and decided to reconstitute it.

This is about the stupidest simplest way you could generate a Mandelbrot set. It outputs a 512x512 raw RGB file, which you can view using ImageMagick by running:

    convert -size 512x512 -depth 8 rgb:mandel.raw mandel.png
    display mandel.png

Here's the C:

#include <stdio.h>
#include <assert.h>

#define PALETTEENTRIES 8

unsigned char palette[PALETTEENTRIES][3] =
{
    { 0, 0, 0 },
    { 255, 0, 0 },
    { 0, 255, 0 },
    { 0, 0, 255 },
    { 255, 255, 0 },
    { 255, 0, 255 },
    { 255, 255, 0 },
    { 0, 255, 255 }
};


// Takes a real and imaginary part of "c"
int EvalMandel(double cr, double ci)
{
    int times = 0;
    double zr = 0;
    double zi = 0;

    // We know the solution will diverge when the length
    // is > 2, but this avoids a square root;
    while (zr*zr+zi*zi < 4 && times < 1024)
    {
        double tzr = zr * zr - zi * zi + cr;
        zi = 2 * zr * zi + ci;
        zr = tzr;
        ++times;
    }
    return times - 1;
}

int main(int argc, char**argv)
{
    double x, y;
    FILE *f = fopen("mandel.raw", "wb");
    assert(f);

    for (y = -2.0; y < 2.0; y += 4.0/512.0)
    {
        for (x = -2.0; x < 2.0; x += 4.0/512.0)
        {
            int c = EvalMandel(x, y);
            c %= PALETTEENTRIES;
            fwrite(palette[c], 3, 1, f);
        }
    }
    fclose(f);
    return 0;
}

And a Makefile

all : mandel
    ./mandel
    convert -size 512x512 -depth 8 rgb:mandel.raw mandel.png
    display mandel.png

mandel : mandel.c
    gcc -o mandel mandel.c