Skip to content

Commit 5394d66

Browse files
Ariana1729berquist
authored andcommitted
Added monte carlo in bash (#519)
1 parent 84aaa36 commit 5394d66

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env bash
2+
inCircle() {
3+
local ret
4+
local mag
5+
((ret = 0))
6+
if (($1 ** 2 + $2 ** 2 < 1073676289)); then # 1073676289 = 32767 ** 2
7+
((ret = 1))
8+
fi
9+
printf "%d" $ret
10+
}
11+
12+
monteCarlo() {
13+
local count
14+
local i
15+
((count = 0))
16+
for ((i = 0; i < $1; i++)); do
17+
if (($(inCircle RANDOM RANDOM) == 1)); then
18+
((count++))
19+
fi
20+
done
21+
echo "scale = 8; 4 * $count / $1" | bc
22+
}
23+
24+
est=$(monteCarlo 10000)
25+
echo "The estimate of pi is $est"
26+
echo "Percentage error: $(echo "scale = 8; 100 * sqrt( ( 1 - $est / (4*a(1)) ) ^ 2 )" | bc -l)"

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ each point is tested to see whether it's in the circle or not:
8787
[import:3-5, lang:"lisp"](code/clisp/monte-carlo.lisp)
8888
{% sample lang="asm-x64" %}
8989
[import:21-32, lang:"asm-x64"](code/asm-x64/monte_carlo.s)
90+
{% sample lang="bash" %}
91+
[import:2-10, lang:"bash"](code/bash/monte_carlo.bash)
9092
{% endmethod %}
9193

9294
If it's in the circle, we increase an internal count by one, and in the end,
@@ -173,6 +175,8 @@ Feel free to submit your version via pull request, and thanks for reading!
173175
[import, lang:"lisp"](code/clisp/monte-carlo.lisp)
174176
{% sample lang="asm-x64" %}
175177
[import, lang:"asm-x64"](code/asm-x64/monte_carlo.s)
178+
{% sample lang="bash" %}
179+
[import, lang:"bash"](code/bash/monte_carlo.bash)
176180
{% endmethod %}
177181

178182

0 commit comments

Comments
 (0)