From 0e3e665fe14ae5c46ba8d677191bd08a7c683554 Mon Sep 17 00:00:00 2001 From: Gorzoid Date: Fri, 5 Oct 2018 12:01:21 +0100 Subject: [PATCH 1/2] Fixed random code Should only produce numbers in rande 0 -> radius not -1 -> +1 --- contents/monte_carlo_integration/code/c/monte_carlo.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/contents/monte_carlo_integration/code/c/monte_carlo.c b/contents/monte_carlo_integration/code/c/monte_carlo.c index b63896dd3..abd1a87e9 100644 --- a/contents/monte_carlo_integration/code/c/monte_carlo.c +++ b/contents/monte_carlo_integration/code/c/monte_carlo.c @@ -13,8 +13,8 @@ void monte_carlo(int samples) { 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; @@ -30,7 +30,10 @@ void monte_carlo(int 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; } From 8d01d9b81b220c77bfe49b017b9e489c42156eb6 Mon Sep 17 00:00:00 2001 From: Gorzoid Date: Fri, 5 Oct 2018 12:05:01 +0100 Subject: [PATCH 2/2] Change return value monte_carlo should return a double, printing code should be in main --- contents/monte_carlo_integration/code/c/monte_carlo.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/contents/monte_carlo_integration/code/c/monte_carlo.c b/contents/monte_carlo_integration/code/c/monte_carlo.c index abd1a87e9..961c2f546 100644 --- a/contents/monte_carlo_integration/code/c/monte_carlo.c +++ b/contents/monte_carlo_integration/code/c/monte_carlo.c @@ -8,7 +8,7 @@ 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; @@ -21,10 +21,7 @@ void monte_carlo(int samples) { } } - 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() {