Skip to content

Commit f9158d4

Browse files
authored
Merge pull request #456 from Gorzoid/monte_carlo_c_fix
Monte carlo C fix
2 parents ebc4caf + 8d01d9b commit f9158d4

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed

contents/monte_carlo_integration/code/c/monte_carlo.c

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,29 @@ bool in_circle(double x, double y, double radius) {
88
return x * x + y * y < radius * radius;
99
}
1010

11-
void monte_carlo(int samples) {
11+
double monte_carlo(int samples) {
1212
double radius = 1.0;
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;
2121
}
2222
}
2323

24-
double estimate = 4.0 * count / (samples * radius * radius);
25-
26-
printf("The estimate of pi is %f\n", estimate);
27-
printf("Percentage error: %0.2f%\n", 100 * fabs(M_PI - estimate) / M_PI);
24+
return 4.0 * count / samples;
2825
}
2926

3027
int main() {
3128
srand(time(NULL));
3229

33-
monte_carlo(1000000);
34-
30+
double estimate = monte_carlo(1000000);
31+
32+
printf("The estimate of pi is %f\n", estimate);
33+
printf("Percentage error: %0.2f%\n", 100 * fabs(M_PI - estimate) / M_PI);
34+
3535
return 0;
3636
}

0 commit comments

Comments
 (0)