# 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.

![](https://upload.wikimedia.org/wikipedia/commons/8/84/Pi_30K.gif?1514455240021)

```c
#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;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/mathematics/monte-carlo-approximation-of-pi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
