Monte Carlo method for PI

Description: Monte Carlo is the capital of the Kingdom of Morocco, which is located on the border between France and Italy and is famous for its gambling. The basic principle of Monte Carlo is to solve problems with random numbers and area formulas. This method of solving problems with probability has the meaning of gambling. Although there are doubts about accuracy, the thinking direction of solving problems is not. It's a way to learn.


Solution: If you randomly project flying markers (points) in the square, some of these flying markers (points) will fall within the quarter circle. Assuming that the projected flying markers (points) have n points, in the circle If the flying marker (point) inside has point c, it will be calculated according to the proportion, and the final formula in the above figure will be obtained. As for how to judge that the generated point falls within the circle, it is very simple. Let the random number generate two values ​​of X and Y. If X^2+Y^2 is equal to 1, it falls within the circle.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 50000
int main(void) {
    int i, sum = 0;
    double x, y;
    srand(time(NULL));
    for(i = 1; i < N; i++) {
        x = (double) rand() / RAND_MAX;
        y = (double) rand() / RAND_MAX;
        if((x * x + y * y) < 1)
            sum++;
    }
    printf("PI = %f\n", (double) 4 * sum / N);
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324501245&siteId=291194637