Skip to content

Commit b537da3

Browse files
authored
Added Monte Carlo integration in Coconut (algorithm-archivists#733)
1 parent c6b76e1 commit b537da3

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import math
2+
import random
3+
4+
data point(x, y):
5+
def __abs__(self) = (self.x, self.y) |> map$(pow$(?, 2)) |> sum |> math.sqrt
6+
7+
def in_circle(p is point, radius = 1):
8+
"""Return True if the point is in the circle and False otherwise."""
9+
return abs(p) < radius
10+
11+
def monte_carlo(n_samples, radius = 1) = (range(n_samples)
12+
|> map$(-> point(random.uniform(0, radius), random.uniform(0, radius)))
13+
|> filter$(in_circle$(?, radius))
14+
|> tuple
15+
|> len) * 4 / n_samples
16+
17+
if __name__ == '__main__':
18+
19+
samples = 100_000
20+
21+
print(f"Using {samples:_} samples.")
22+
23+
pi_estimate = monte_carlo(samples)
24+
percent_error = 100*abs(math.pi - pi_estimate)/math.pi
25+
26+
print("The estimate of pi is: {:.3f}".format(pi_estimate))
27+
print("The percent error is: {:.3f}".format(percent_error))
28+

contents/monte_carlo_integration/monte_carlo_integration.md

+4
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ each point is tested to see whether it's in the circle or not:
9797
<p>
9898
<img class="center" src="code/scratch/InCircle.svg" style="width:40%" />
9999
</p>
100+
{% sample lang="coco" %}
101+
[import:4-9, lang:"coconut"](code/coconut/monte_carlo.coco)
100102
{% endmethod %}
101103

102104
If it's in the circle, we increase an internal count by one, and in the end,
@@ -202,6 +204,8 @@ The code snippets were taken from this [scratch project](https://scratch.mit.edu
202204
<p>
203205
<img class="center" src="code/scratch/Algorithm.svg" style="width:100%" />
204206
</p>
207+
{% sample lang="coco" %}
208+
[import, lang:"coconut"](code/coconut/monte_carlo.coco)
205209
{% endmethod %}
206210

207211
<script>

0 commit comments

Comments
 (0)