Skip to content

Instantly share code, notes, and snippets.

@localmin
Last active October 18, 2017 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save localmin/42930babc8a6d050786d69ff0a47345d to your computer and use it in GitHub Desktop.
Save localmin/42930babc8a6d050786d69ff0a47345d to your computer and use it in GitHub Desktop.
Get Pi by Monte Carlo method.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
unsigned int next;
unsigned int A = 1103515245, C = 12345, M = 2147482648;
double my_rand(void){
next = (next * A + C) % M;
return next;
}
void my_srand(unsigned int seed){
next = seed;
}
int main(int argc, char *argv[]){
int i, n, k;
double x, y, pi;
n = atoi(argv[1]);
k = 0;
my_srand((unsigned)time(NULL));
for(i=0; i<n; i++){
x = my_rand()/(M-1);
y = my_rand()/(M-1);
if(x*x + y*y <= 1){
k++;
}
}
pi = (double)4*k/n;
printf("pi = %lf\n", pi);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment