mandelbrot

categories: blog

A very nice minimal code size implementation of the Mandelbrot algorithm by Ken Peril I found here

main(k){float i,j,r,x,y=-16;while(puts(""),y++<15)for(x
=0;x++<84;putchar(" .:-;!/>)|&IH%*#"[k&15]))for(i=k=r=0;
j=r*r-i*i-2+x/25,i=2*r*i+y/10,j*j+i*i<11&&k++<111;r=j);}

It is very interesting to see what techniques where applied to minimize the amount of source code bytes. When I tried out the code, not knowing what pattern it would output I was very find to see a Mandelbrot pattern printed to my terminal :)

The code translates to this which outputs the exact same bytes:

#include <stdio.h>

int main(int argc, char **argv)
{
int k,x,y;
float i,j,r;
char *chars;
chars = " .:-;!/>)|&IH%*#";
for(y=-15;y<16;y++) {
puts("");
for(x=1;x<=84;x++) {
i=0;
r=0;
for(k=0;k<112;k++) {
j=r*r-i*i-2+x/25.0f;
i=2*r*i+y/10.0f;
if (j*j+i*i>=11) {
break;
}
r=j;
}
putchar(chars[k&15]);
}
}
puts("");
return 0;
}

y and x iterate over rows and colums on the terminal. They are scaled by 1/25 and 1/10 respectively. 112 is the maximum iteration number and only has the requirement of being divisible by 16 (the number of characters for the ascii art). A difference to the original algorithm is the -2 in calculating j but this is just to shift the x values to the right on output. Alternatively one could also just iterate x eg from -50 to 34 instead from 1 to 84 which would give a similar output. To compensate for the shift and to also draw points close to the border 11 was chosen as a good stopping criterion for beautiful output. Normally one would check for jj+ii being less than or equal to 4 but this would mean that for border points the algorithm would terminate in the 1st iteration, painting those points the same as the ones that do not lie in the Mandelbrot set.

View Comments
blog comments powered by Disqus