# Monte Carlo Approximation of PI

Monte Carlo method for computing π is to draw a circle inscribed in a square, and randomly place dots in the square. The ratio of dots inside the circle to the total number of dots will approximately equal π/4.

``````#include stdio.h
#include stdlib.h
#include stdbool.h
#include ctype.h
#include string.h

bool isInteger(char s, bool accept_neg) {
int i = 0;
s[strlen(s)] = '0';
if (accept_neg && i  strlen(s) && s[0] == '-') i++;
for (; i  strlen(s); i++) {
if (!isdigit(s[i])) return false;
}
return true;
}

char  get_input() {
printf(Enter the number of iterations to run );
char input[250];
scanf(%[^n],input);
}

int getNIter() {
while (1) {
printf(Enter the number of iterations to run );
char input[250];
scanf(%[^n],input);
input[strlen(input)] = 'n';

if (isInteger(input, false)) {
return atoi(input);
}
}
}

int getSeed() {
while (1) {
printf(Enter the seed for the random number generator );
char input[250];
scanf(%[^n],input);
input[strlen(input)] = '0';

if (isInteger(input, false)) {
return atoi(input);
}
free(input);
}
}

double gen_rand() {
double High = 1.00;
double Low = -1.00;
return Low + (((double)rand())  (((double)RAND_MAX)  (High - Low)));
}

bool isInCircle(double x, double y) {
return ((xx) + (yy)) = 1;
}

void runSimulation(int userSeed, int runIteration) {
double mPoints = 0;
srand(userSeed);
for (int i = 0; i  runIteration; ++i) {
if (isInCircle(gen_rand(), gen_rand())) {
mPoints++;
}
}

double piValue = (mPoints  (double)runIteration  4);
printf(The value of pi is %.3lf.n, piValue);
}

int main() {

int userSeed = getSeed();
int nIter = getNIter();
runSimulation(userSeed, nIter);

fflush(stdin);
getchar();
return 0;
}``````

Last updated