#include <iostream> //need this by default for cin
#include <math.h> //includes math functions
#include <cmath> //includes basic math
#include <cfloat> //includes floating point numbers
#include <iomanip> //includes setprecision for decimal places
#include <cstdlib> //needed for rand and srand functions
#include <ctime> //needed for time function used to seed generator
#include <climits>
using namespace std;
int main()
{
cout << "The purpose of this program is to estimate pi using the monte "
"carlo method and a random number generator" << endl << endl;
unsigned seed = time(0);
srand(seed);
int trialcount = 0;
int trials;
float accuracy;
const float pi = 3.14159265;
cout << "The value of PI can be found as the ratio of areas of a circle of radius r located within a square of side 2r" << endl;
cout << "This program runs a MonteCarlo Simulation that generates numbers located randomly within a square" << endl;
cout << "The count of values within the square and the count of numbers within the circle approximate their areas" << endl;
cout << "An input value of radius determines the size of the circle and square" << endl;
cout << "The user specifies how many trials or test runs are desired" << endl << endl;
cout << "The true value of PI to 8 decimal places is 3.14159265" << endl << endl;
cout << endl;
cout << "How many trials would you like? ";
cin >> trials;
cout << endl << endl;
cout << "Square count gives the Total number of random samples (they are within the square)" << endl;
cout << "Circle count gives the number of random samples that also fall within the circle" << endl << endl;
while (trialcount != trials)
{
accuracy = 0.1;
cout << "Trial " << trialcount + 1 << endl;
cout << "Accuracy \t\t" << "Square Count \t\t" << "Circle Count \t\t" << "Pi" << endl << endl;
for (int j = 0; j < 6; j++)
{
accuracy /= 10;
float randpi = 0;
int squarecount = 0;
int circlecount = 0;
int stopAt = (INT_MAX >> 8);
for (int i = 0; (randpi >= pi + accuracy || randpi <= pi - accuracy) && i < stopAt; i++)
{
float x = ((float)(rand() % 32768) / 32767);
float y = ((float)(rand() % 32768) / 32767);
squarecount++;
if ((x * x) + (y * y) <= 1.0 )
{
circlecount++;
}
randpi = float(4 * circlecount) / squarecount;
}
cout << setprecision(8) << fixed << accuracy << " \t\t" << squarecount << " \t\t" << circlecount << " \t\t" << randpi << endl << endl;
}
trialcount++;
}
}