Skip to content

Commit 0e3e665

Browse files
committed
Fixed random code
Should only produce numbers in rande 0 -> radius not -1 -> +1
1 parent 684475c commit 0e3e665

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

contents/monte_carlo_integration/code/c/monte_carlo.c

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ void monte_carlo(int samples) {
1313
int count = 0;
1414

1515
for (int i = 0; i < samples; ++i) {
16-
double x = (double)rand() * 2.0 / RAND_MAX - 1.0;
17-
double y = (double)rand() * 2.0 / RAND_MAX - 1.0;
16+
double x = (double)rand() * radius / RAND_MAX;
17+
double y = (double)rand() * radius / RAND_MAX;
1818

1919
if (in_circle(x, y, radius)) {
2020
count += 1;
@@ -30,7 +30,10 @@ void monte_carlo(int samples) {
3030
int main() {
3131
srand(time(NULL));
3232

33-
monte_carlo(1000000);
34-
33+
double estimate = monte_carlo(1000000);
34+
35+
printf("The estimate of pi is %f\n", estimate);
36+
printf("Percentage error: %0.2f%\n", 100 * fabs(M_PI - estimate) / M_PI);
37+
3538
return 0;
3639
}

0 commit comments

Comments
 (0)