Last active
October 18, 2017 15:46
-
-
Save localmin/42930babc8a6d050786d69ff0a47345d to your computer and use it in GitHub Desktop.
Get Pi by Monte Carlo method.
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 <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