Skip to content

Commit 7b92b39

Browse files
c252jiegillet
authored andcommitted
implemented monte carlo integration in nim (#356)
1 parent 258b108 commit 7b92b39

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import random
2+
import math
3+
4+
randomize()
5+
6+
proc in_circle(x,y,radius: float): bool =
7+
return x * x + y * y < radius * radius
8+
9+
proc monte_carlo(samples: int): float =
10+
const radius: float = 1
11+
var count: int = 0
12+
13+
for i in 0 .. < samples:
14+
var
15+
x: float = random(radius)
16+
y: float = random(radius)
17+
18+
if in_circle(x,y,radius):
19+
count += 1
20+
21+
var pi_estimate: float = 4 * count / samples
22+
return pi_estimate
23+
24+
let estimate: float = monte_carlo(1000000)
25+
26+
echo "the estimate of pi is ", estimate
27+
echo "percent error: ", 100 * (abs(estimate - PI)/PI)

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ each point is tested to see whether it's in the circle or not:
6565
[import:5-7, lang:"python"](code/python/monte_carlo.py)
6666
{% sample lang="cs" %}
6767
[import:23-23, lang:"csharp"](code/csharp/Circle.cs)
68+
{% sample lang="nim" %}
69+
[import:6-7, lang:"nim"](code/nim/monte_carlo.nim)
6870
{% endmethod %}
6971

7072
If it's in the circle, we increase an internal count by one, and in the end,
@@ -129,9 +131,12 @@ Feel free to submit your version via pull request, and thanks for reading!
129131
[import, lang:"csharp"](code/csharp/Circle.cs)
130132
##### Program.cs
131133
[import, lang:"csharp"](code/csharp/Program.cs)
134+
{% sample lang="nim" %}
135+
[import, lang:"nim"](code/nim/monte_carlo.nim)
132136
{% endmethod %}
133137

134138

139+
135140
<script>
136141
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
137142
</script>

0 commit comments

Comments
 (0)