Skip to content

Instantly share code, notes, and snippets.

@paranlee
Created May 27, 2021 17:21
Show Gist options
  • Save paranlee/6145d2b6a756b84f816fafc0c2a18417 to your computer and use it in GitHub Desktop.
Save paranlee/6145d2b6a756b84f816fafc0c2a18417 to your computer and use it in GitHub Desktop.
Program to compute Pi using Monte Carlo methods
#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