Skip to content

Instantly share code, notes, and snippets.

@guidanoli
Created August 28, 2019 03:16
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 guidanoli/f6d78c679887c607697cc6c59ff31289 to your computer and use it in GitHub Desktop.
Save guidanoli/f6d78c679887c607697cc6c59ff31289 to your computer and use it in GitHub Desktop.
Approximation of Pi by probability
/*
* 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