Skip to content

Commit 3db41a5

Browse files
Gathrosleios
authored andcommitted
Adding a C Monte Carlo implementation. (#121)
* Adding monte_carlo.c * changing monte_carlo.md * naming fix for monte_carlo.c * adding precentage error to monte_carlo.c * updating monte_carlo.md
1 parent 4e3bb48 commit 3db41a5

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <math.h>
2+
#include <stdio.h>
3+
#include <stdbool.h>
4+
#include <stdlib.h>
5+
#include <time.h>
6+
7+
bool in_circle(double x, double y, double radius) {
8+
return x * x + y * y < radius * radius;
9+
}
10+
11+
void monte_carlo(int samples, double radius) {
12+
int count = 0;
13+
14+
for (int i = 0; i < samples; ++i) {
15+
double x = (double)rand() * 2.0 / RAND_MAX - 1.0;
16+
double y = (double)rand() * 2.0 / RAND_MAX - 1.0;
17+
18+
if (in_circle(x, y, radius)) {
19+
count += 1;
20+
}
21+
}
22+
23+
double estimate = 4.0 * count / (samples * radius * radius);
24+
25+
printf("The estimate of pi is %f\n", estimate);
26+
printf("Which has an error of %0.2f%\n", 100 * (M_PI - estimate) / M_PI);
27+
}
28+
29+
int main() {
30+
srand(time(NULL));
31+
32+
monte_carlo(1000000, 1.0);
33+
34+
return 0;
35+
}

chapters/monte_carlo/monte_carlo.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,8 @@ each point is tested to see whether it's in the circle or not:
3939
{% method %}
4040
{% sample lang="jl" %}
4141
[import:2-8, lang:"julia"](code/julia/monte_carlo.jl)
42+
{% sample lang="c" %}
43+
[import:7-9, lang:"c_cpp"](code/c/monte_carlo.c)
4244
{% sample lang="hs" %}
4345
[import:7-7, lang:"haskell"](code/haskell/monteCarlo.hs)
4446
{% endmethod %}
@@ -75,6 +77,9 @@ Feel free to submit your version via pull request, and thanks for reading!
7577
{% sample lang="jl" %}
7678
### Julia
7779
[import, lang:"julia"](code/julia/monte_carlo.jl)
80+
{% sample lang="c" %}
81+
### C
82+
[import, lang:"c_cpp"](code/c/monte_carlo.c)
7883
{% sample lang="hs" %}
7984
### Haskell
8085
[import, lang:"haskell"](code/haskell/monteCarlo.hs)

0 commit comments

Comments
 (0)