/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/**************************************************************************

 * Copyright (C) DMGualtieri 2014 <gualtieri@ieee.org>
 * 
 * picalc 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.
 * 
 * Picalc 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 <http://www.gnu.org/licenses/>.

 **************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

long int trials;
long int drops;
long int i;
long int j;
double x;
double y;
double r;
double count;
FILE *outdata;

/* Determination of pi by random dots in a unit circle

This is essentially a Monte Carlo calculation.  We draw a circle in a square,
we drop grains of sand onto them and count how many land inside the circle.
Since the area of the square is 1 (if its sides are one), and the area of the
circle is (pi/4), then pi is four times the ratio of the number of grains
that land inside the circle to the total number of grains.

*/

int main(int argc, char *argv[])
{

if (argc<2)
{
printf("Usage: picalc number_of_grain_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]);
/* It's always good to check RAND_MAX to see how many random numbers we can
   extract without a problem */
printf("\nTrials = %ld   Drops = %ld   Rand_Max = %d\n",trials,drops,RAND_MAX);
for(j=0;j<trials;j++)
{
count = 0;
for(i=0;i<drops;i++)
{
// get x and y.  We just use one quadrant of the circle.  Results are the same.
x = (double)rand()/(double)RAND_MAX;
y = (double)rand()/(double)RAND_MAX;
r = sqrt((x*x)+(y*y));
if(r<=1)
{
count = count+1;
}
}
fprintf(outdata,"%f\n",4*count/(double)drops);
if(j%1000 == 0)
{
printf("loop %ld finished\n",j);
}
}

//Close output file
fclose(outdata);

return (0);

}
