/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/**************************************************************************
* Copyright (C) DMGualtieri 2010
*
* Buffon_Needle is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Buffon_Needle is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see .
**************************************************************************/
#include
#include
#include
#include
long int trials;
long int drops;
long int i;
long int j;
double count;
FILE *outdata;
/* Buffon's Needle determination of pi
see http://en.wikipedia.org/wiki/Buffon%27s_needle
Our needle length is L = 1, and the space between boards is d = 1.
We take random samples of needles dropped on a single board
at random angles, and we find the fraction that traverse the cracks
between boards. The boards extend in the y-axis, so y is irrelevant,
and we only calculate using x. Pi is given as twice the ratio of the
total trials to the number that traverse a crack between boards.
Note the irony of this calculation - We're estimating pi, but pi is part
of the program!
*/
double drop_needle(void)
{
//Note L=d=1
double angle;
double center;
double position1;
double position2;
double count_this;
//The model has three boards x[0..1], x[1..2], x[2..3]
//We drop needles on the center board
angle = (3.1415926535/2)*(double)rand()/(double)RAND_MAX;
center = 1.0 + ((double)rand()/(double)RAND_MAX);
position1 = center + (0.5)*cos(angle);
position2 = center - (0.5)*cos(angle);
//Note condition statement - We want limits that are a board's length, not shorter
if((position1<=2)&&(position2>1))
{
count_this=0;
}
else
{
count_this=1;
}
return(count_this);
}
int main(int argc, char *argv[])
{
if (argc<2)
{
printf("Usage: Buffon_Needle number_of_needle_drops_per_trial number_of_trials\n");
exit(1);
}
//Seed random number generator
srand ( (unsigned)time ( NULL ) );
//Open output datafile
if ((outdata = fopen("pi_data.txt","w"))==NULL)
{printf ("\nOutput file cannot be opened.\n");
exit (1);}
else
{
printf("Output file = pi_data.txt");
}
drops = atol(argv[1]);
trials = atol(argv[2]);
printf("\nTrials = %ld Drops = %ld\n",trials,drops);
for(j=0;j