File tree Expand file tree Collapse file tree 1 file changed +12
-13
lines changed
contents/monte_carlo_integration/code/c Expand file tree Collapse file tree 1 file changed +12
-13
lines changed Original file line number Diff line number Diff line change 4
4
#include <stdlib.h>
5
5
#include <time.h>
6
6
7
- bool in_circle (double x , double y , double radius ) {
8
- return x * x + y * y < radius * radius ;
7
+ bool in_circle (double x , double y ) {
8
+ return x * x + y * y < 1 ;
9
9
}
10
10
11
- double monte_carlo (int samples ) {
12
- double radius = 1.0 ;
13
- int count = 0 ;
11
+ double monte_carlo (unsigned int samples ) {
12
+ unsigned int count = 0 ;
14
13
15
- for (int i = 0 ; i < samples ; ++ i ) {
16
- double x = (double )rand () * radius / RAND_MAX ;
17
- double y = (double )rand () * radius / RAND_MAX ;
14
+ for (unsigned int i = 0 ; i < samples ; ++ i ) {
15
+ double x = (double )rand () / RAND_MAX ;
16
+ double y = (double )rand () / RAND_MAX ;
18
17
19
- if (in_circle (x , y , radius )) {
18
+ if (in_circle (x , y )) {
20
19
count += 1 ;
21
20
}
22
21
}
@@ -28,9 +27,9 @@ int main() {
28
27
srand (time (NULL ));
29
28
30
29
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
-
30
+
31
+ printf ("The estimate of pi is %g \n" , estimate );
32
+ printf ("Percentage error: %0.2f%% \n" , 100 * fabs (M_PI - estimate ) / M_PI );
33
+
35
34
return 0 ;
36
35
}
You can’t perform that action at this time.
0 commit comments