These are some nice little programs to create PBM pictures of classic fractals.

You will need pbmtool.* (see below) for compiling the following programs. Yes, some code is stolen from pbmholstein.c by John Walker and bitarray.c from a rather old version of the snippets package. In the meanwhile I found the newer .

/* Create a sierpinski gasket using recursion */ #include <stdio.h> #include "pbmtool.h" #define WURZ3 1.7320508 void sierpinski(int x,int y, /*Position of lower left corner*/ int generation) { if(generation==0) setpixel(x,y); else{ int i,power=1; sierpinski(x,y,generation-1); for(i=0;i<(generation-2);i++)power*=2; sierpinski(x+2*power,y,generation-1); sierpinski(x+power,(int) (y+WURZ3*power),generation-1); /*y mit 1/2Wurzel3*/ } } main(int argc,char ** argv) { int x,y,maxgen,size; maxgen=atoi(argv[1]); size=1;for(x=0;x<maxgen;x++)size*=2; for(x=0;x<size;x++) for(y=0;y<size;y++) clearpixel(x,y); sierpinski(0,0,maxgen); WritePbm(size,size*0.5*WURZ3+1); }
There are other ways of creating the sierpinski gasket. The following two are similar to those in the book "Fractals Everywhere" by Michael Barnsley.
/* create a part of the v. Koch snow flake using recursion */ #include <stdio.h> #include <math.h> #include <values.h> #include "pbmtool.h" #define WURZ2 1.4142136 #define WURZ3 1.7320508 double m_sin(int alfa) { return sin(M_PI*(double)alfa/180.0);} double m_cos(int alfa) { return cos(M_PI*(double)alfa/180.0);} void koch(int x,int y, /*Position of lower left corner*/ int alfa, int generation) { if(generation==0) setpixel(x,y); else{ int i,len=1; if(alfa>=360)alfa-=360; if(alfa<0)alfa+=360; for(i=1;i<generation;i++)len*=3; /* Length of one branch */ koch(x,y,alfa,generation-1); koch(x+len*m_cos(alfa),y+len*m_sin(alfa),alfa+60,generation-1); koch(x+len*(m_cos(alfa)+m_cos(alfa+60)),y+len*(m_sin(alfa+60)+m_sin(alfa)),alfa-60,generation-1); koch(x+2*len*m_cos(alfa),y+2*len*m_sin(alfa),alfa,generation-1); } } main(int argc,char ** argv) { int x,y,maxgen,size; maxgen=atoi(argv[1]); size=1;for(x=0;x<maxgen;x++)size*=3; for(x=0;x<size;x++) for(y=0;y<size;y++) clearpixel(x,y); koch(0,0,0,maxgen); WritePbm(size,0.17*WURZ3*size); /* 0.17 == 1/6 remember _/\_ */ }
Generalized Koch curves
/* a little mandelbrot program */ #include<stdio.h> #define MAXITER 10000 int tepoint(double r,double i) { int zeahl; double re=0, oldre=0, im=0, oldim=0, betr; for(zeahl=1;zeahl<MAXITER;zeahl++){ re= oldre*oldre - oldim*oldim +r; im= 2*oldre*oldim+i; betr=re*re+im*im; if(betr>5) return (1); /* outside */ oldre=re; oldim=im; } return(0); /* inside */ } main() { FILE* outfile; int count; double i,j; outfile=fopen("mandel.pbm","w"); fprintf(outfile,"P1 1201 800 \n"); for(i=-1;i<1;i+=0.0025) for(j=-2;j<1;j+=0.0025){ count++; fprintf(outfile," %d",tepoint(j,i)); if(count%20==0)fprintf(outfile,"\n"),fflush(outfile); } close(outfile); }
Some more:

Jürgen Dollinger