diff --git a/contents/monte_carlo_integration/code/c/monte_carlo.c b/contents/monte_carlo_integration/code/c/monte_carlo.c index 961c2f546..9920ff55c 100644 --- a/contents/monte_carlo_integration/code/c/monte_carlo.c +++ b/contents/monte_carlo_integration/code/c/monte_carlo.c @@ -4,19 +4,18 @@ #include #include -bool in_circle(double x, double y, double radius) { - return x * x + y * y < radius * radius; +bool in_circle(double x, double y) { + return x * x + y * y < 1; } -double monte_carlo(int samples) { - double radius = 1.0; - int count = 0; +double monte_carlo(unsigned int samples) { + unsigned int count = 0; - for (int i = 0; i < samples; ++i) { - double x = (double)rand() * radius / RAND_MAX; - double y = (double)rand() * radius / RAND_MAX; + for (unsigned int i = 0; i < samples; ++i) { + double x = (double)rand() / RAND_MAX; + double y = (double)rand() / RAND_MAX; - if (in_circle(x, y, radius)) { + if (in_circle(x, y)) { count += 1; } } @@ -28,9 +27,9 @@ int main() { srand(time(NULL)); double estimate = monte_carlo(1000000); - - printf("The estimate of pi is %f\n", estimate); - printf("Percentage error: %0.2f%\n", 100 * fabs(M_PI - estimate) / M_PI); - + + printf("The estimate of pi is %g\n", estimate); + printf("Percentage error: %0.2f%%\n", 100 * fabs(M_PI - estimate) / M_PI); + return 0; }