diff --git a/contents/monte_carlo_integration/code/c/monte_carlo.c b/contents/monte_carlo_integration/code/c/monte_carlo.c index b63896dd3..961c2f546 100644 --- a/contents/monte_carlo_integration/code/c/monte_carlo.c +++ b/contents/monte_carlo_integration/code/c/monte_carlo.c @@ -8,29 +8,29 @@ bool in_circle(double x, double y, double radius) { return x * x + y * y < radius * radius; } -void monte_carlo(int samples) { +double monte_carlo(int samples) { double radius = 1.0; int count = 0; for (int i = 0; i < samples; ++i) { - double x = (double)rand() * 2.0 / RAND_MAX - 1.0; - double y = (double)rand() * 2.0 / RAND_MAX - 1.0; + double x = (double)rand() * radius / RAND_MAX; + double y = (double)rand() * radius / RAND_MAX; if (in_circle(x, y, radius)) { count += 1; } } - double estimate = 4.0 * count / (samples * radius * radius); - - printf("The estimate of pi is %f\n", estimate); - printf("Percentage error: %0.2f%\n", 100 * fabs(M_PI - estimate) / M_PI); + return 4.0 * count / samples; } int main() { srand(time(NULL)); - monte_carlo(1000000); - + 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); + return 0; }