-
-
Save guidanoli/f6d78c679887c607697cc6c59ff31289 to your computer and use it in GitHub Desktop.
Approximation of Pi by probability
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
/* | |
* pi.c | |
* | |
* Approximation of Pi by the probability | |
* of a point to fall into the circle of | |
* a circumscribed square in the xy-plane. | |
* | |
* Inspired by Simulation Fifth Edition | |
* Book by Sheldon Ross | |
*/ | |
#include <stdio.h> | |
#include <math.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
int main(int argc, char ** argv) | |
{ | |
unsigned long long nsamples, inside_cnt = 0; | |
double x, y; | |
srand((unsigned) time(NULL)); | |
assert(argc == 2); | |
nsamples = atoi(argv[1]); | |
assert(nsamples != 0); | |
for (int i = 0; i < nsamples; ++i) { | |
x = ( 2 * ((double) rand() / RAND_MAX) ) - 1; | |
y = ( 2 * ((double) rand() / RAND_MAX) ) - 1; | |
if (x*x + y*y <= 1) | |
++inside_cnt; | |
} | |
double pi = 4 * ( (double) inside_cnt / (double) nsamples); | |
printf("pi ~= %lf\n", pi); | |
double nu = fabs(pi / M_PI - 1); | |
printf("nu = %lf\n", nu); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment