/* Compilation instructions */
/* gcc -Wall -ansi -pedantic -o Pi_archi_approx Pi_archi_approx.c */
/* This program generates an SVG image, showing Archimede's technique to */
/* approximate pi */
/* One argument can be provided, as the maximum number of approximations desired */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265358979
int main(int argc, char **argv)
{
int i,j,n;
double id,coeff;
FILE *fpt;
double *x, *y;
double R = 40.0;
/* Angle values*/
double alpha, alpha_offset;
int fontsize = 10;
double strokewidth = 0.8;
if (argc == 2)
n = (int)atof(argv[1]);
else
{
n = 10;
}
if (n<3)
{
printf("\n");
fflush(stdout);
exit(1);
}
/* Opening result file*/
fpt = fopen("Pi_archi_approx.svg","w");
fprintf(fpt,"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
fprintf(fpt,"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd \">\n");
fprintf(fpt,"<svg\n");
fprintf(fpt," xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" \n");
fprintf(fpt," xmlns:svg=\"http://www.w3.org/2000/svg\" \n");
fprintf(fpt," xmlns=\"http://www.w3.org/2000/svg\" \n");
fprintf(fpt," width=\"%dpx\" \n",(int)(((n-2)*3+1)*R));
fprintf(fpt," height=\"%dpx\" \n",(int)(4.5*R));
fprintf(fpt," >\n");
for (i=3;i<=n;i++)
{
id = (double) i;
x = (double *)malloc(i*sizeof(double));
y = (double *)malloc(i*sizeof(double));
fprintf(fpt," <g>\n");
fprintf(fpt," <circle cx=\"%f\" cy=\"%f\" r=\"%f\" ",((id-2)*3-0.75)*R,2.5*R,R);
fprintf(fpt,"stroke=\"black\" stroke-width=\"%f\" fill=\"none\"/>\n",strokewidth);
fprintf(fpt," <polygon points=\"");
alpha_offset = -PI/2 + ((i%2)==0) * PI/id;
for (j=0;j<i;j++)
{
alpha = alpha_offset + 2*j*PI/id;
x[j] = cos(alpha);
y[j] = sin(alpha);
fprintf(fpt,"%f,%f ",R*x[j]+((id-2)*3-0.75)*R,R*(y[j]+2.5));
}
fprintf(fpt,"\" fill=\"none\" stroke=\"black\" stroke-width=\"%f\"/>\n",strokewidth);
coeff = 2.0/sqrt((x[0]+x[1])*(x[0]+x[1]) + (y[0]+y[1])*(y[0]+y[1]));
fprintf(fpt," <polygon points=\"");
for (j=0;j<i;j++)
{
fprintf(fpt,"%f,%f ",R*coeff*x[j]+((id-2)*3-0.75)*R,R*(coeff*y[j]+2.5));
}
fprintf(fpt,"\" fill=\"none\" stroke=\"black\" stroke-width=\"%f\"/>\n",strokewidth);
free(x);
free(y);
fprintf(fpt," <text x = \"%f\" y = \"%f\" text-anchor=\"middle\" fill = \"black\" font-size = \"%d\">\n",
((id-2)*3-0.75)*R,4*R,fontsize);
fprintf(fpt," n = %d\n",i);
fprintf(fpt," </text>\n");
fprintf(fpt," </g>\n");
}
fprintf(fpt,"</svg>\n");
fclose(fpt);
return (0);
}