Skip to content

Instantly share code, notes, and snippets.

@413x1nkp
Created October 8, 2024 03:35
Show Gist options
  • Save 413x1nkp/3d0be19749afe84c2dacea24989bc224 to your computer and use it in GitHub Desktop.
Save 413x1nkp/3d0be19749afe84c2dacea24989bc224 to your computer and use it in GitHub Desktop.
Pi estimation using only uniformally random numbers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
double random_uniform(void) { return (double)rand() / (double)RAND_MAX; }
long double estimate_pi(int iter) {
int num_points_in_circle = 0, num_points_total = 0;
for (int i = 0; i < iter; ++i) {
double x = random_uniform();
double y = random_uniform();
long double distance = pow(x, 2) + pow(y, 2);
num_points_in_circle += 1 * (distance <= 1);
num_points_total++;
}
return 4.0 * num_points_in_circle/num_points_total;
}
int main(int argc, char* argv[]) {
srand(time(NULL));
long double res = estimate_pi(atoi(argv[1]));
printf("%Lf\n", res);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment