Created
May 27, 2021 17:21
-
-
Save paranlee/6145d2b6a756b84f816fafc0c2a18417 to your computer and use it in GitHub Desktop.
Program to compute Pi using Monte Carlo methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <math.h> | |
#include <string.h> | |
#define SEED 35791246 | |
int main(int argc, char* argv) { | |
int niter = 1UL << 20; | |
double x, y; | |
/* number of points in the 1st quadrant of unit circle */ | |
int count = 0; | |
double rsqure; | |
printf("Enter the number of iterations used to estimate pi: %d", niter); | |
// scanf("%d", &niter); | |
/* initialize random numbers */ | |
srand(SEED); | |
for (int i = 0; i < niter; i++) { | |
x = (double) rand() / RAND_MAX; | |
y = (double) rand() / RAND_MAX; | |
rsqure = x * x + y * y; | |
// deterministic algorithm, x^2 + y^2 <= 1 | |
if (rsqure <= 1) | |
count++; | |
} | |
double pi = (double) count / niter * 4; | |
printf("# of trials = %d , estimate of pi is %g \n", niter, pi); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment