Mandelbrot – recursion, structure, and makefile
————mason% cat makefile——–
mandelbrot:complex.o mandelbrot.o main.o
gcc -o mandelbrot main.o mandelbrot.o complex.o -lm
main.o:main.c complex.h mandelbrot.h
gcc -c main.c
mandelbrot.o:mandelbrot.c mandelbrot.h
gcc -c mandelbrot.c
complex.o: complex.c complex.h
gcc -c complex.c
clean:
rm *.o mandelbrot
ls-FC
————–mason% cat mandelbrot.h—————
#ifndef mandelbrot_h
#define mandelbrot_h
extern complex_t c;
//check the complex number c is mandelbrot set or not
complex_t mandelbrot(int, complex_t);
#endif
—————–mason% cat mandelbrot.c—————
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include “complex.h”
#include “mandelbrot.h”
//check the complex number c is mandelbrot set or not
complex_t mandelbrot(int n, complex_t c){
complex_t f1;
double a;
//calculate the complex number
if (n==0){
f1.real=c.real;
f1.imag=c.imag;}
else {f1=mandelbrot(n-1,c);
f1=multiply_complex(f1,f1);
f1=add_complex(c,f1);}
a=abs_complex(f1);
// check the complex number is smaller than 10000 or not
if(a==10000||a>10000) {f1.real=10000; f1.imag=10000;};
return f1;
}
——————mason% cat complex.h———————–
#ifndef complex_h
#define complex_h
typedef struct{double real, imag;
} complex_t;
//calculate add two complex numbers
complex_t add_complex(complex_t a1,complex_t a2);
//calculate the product of two complex numbers
complex_t multiply_complex(complex_t a1, complex_t a2);
//abs
double abs_complex(complex_t c);
#endif
——————-mason% cat complex.c————————
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include “complex.h”
//calculate add two complex numbers
complex_t add_complex(complex_t a1,complex_t a2){
complex_t add;
add.real=a1.real+a2.real;
add.imag=a1.imag+a2.imag;
return(add);
}
//calculate the product of two complex numbers
complex_t multiply_complex(complex_t a1, complex_t a2){
complex_t mu;
mu.real=(a1.real*a2.real) – (a1.imag*a2.imag);
mu.imag=(a1.real*a2.imag) + (a1.imag*a2.real);
return (mu);
}
//abs
double abs_complex(complex_t c){
double a;
a=sqrt(c.real*c.real+c.imag*c.imag);
return(a);}
——————————mason% cat main.c————————–
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdint.h>
#include “complex.h”
#include “mandelbrot.h”
complex_t c;
int main(void)
{
complex_t f;
double x,y,a;
int i,r,n=15;
FILE *fp=fopen(“mande.txt”,”w”);
//check every row in the mandelbrot(n)
for(r=0;r<=100;r++)
{ y=-1.12+(r*0.02);
//check every character in the mandelbrot(n)
for(i=0;i<=120;i++)
{ x=-2.0+(i*0.022);
c.real=x;
c.imag=y;
f=mandelbrot(n,c);
if (f.real==10000 && f.imag==10000) fprintf(fp,” “);
else fprintf(fp,”1″);
}
fprintf(fp,”\n”);
}
fclose(fp);
return 0;
}