Skip to content

Commit 0ee2f8e

Browse files
jasmaajiegillet
authored andcommitted
Implement monte carlo in ruby (#361)
* Implement monte carlo in ruby * Fix percent error
1 parent 0b33e67 commit 0ee2f8e

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def in_circle(x, y, radius=1)
2+
# Check if coords are in circle via Pythagorean Thm
3+
return (x*x + y*y) < radius*radius
4+
end
5+
6+
def monte_carlo(n_samples, radius=1)
7+
# estimate pi via monte carlo sampling
8+
in_circle_count = 0.0
9+
10+
for _ in 0...n_samples
11+
# randomly choose coords within square
12+
x = rand()*radius
13+
y = rand()*radius
14+
if in_circle(x, y, radius)
15+
in_circle_count += 1
16+
end
17+
end
18+
19+
# circle area is pi*r^2 and rect area is 4r^2
20+
# ratio between the two is then pi/4 so multiply by 4 to get pi
21+
return 4 * (in_circle_count / n_samples)
22+
23+
end
24+
25+
26+
# Main
27+
pi_estimate = monte_carlo(100000)
28+
percent_error = 100 * (pi_estimate - Math::PI).abs / Math::PI
29+
30+
puts "The estimate of pi is: #{pi_estimate.round(3)}"
31+
puts "The percent error is: #{percent_error.round(3)}"
32+

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ each point is tested to see whether it's in the circle or not:
6767
[import:23-23, lang:"csharp"](code/csharp/Circle.cs)
6868
{% sample lang="nim" %}
6969
[import:6-7, lang:"nim"](code/nim/monte_carlo.nim)
70+
{% sample lang="ruby" %}
71+
[import:1-4, lang:"ruby"](code/ruby/monte_carlo.rb)
7072
{% endmethod %}
7173

7274
If it's in the circle, we increase an internal count by one, and in the end,
@@ -133,6 +135,8 @@ Feel free to submit your version via pull request, and thanks for reading!
133135
[import, lang:"csharp"](code/csharp/Program.cs)
134136
{% sample lang="nim" %}
135137
[import, lang:"nim"](code/nim/monte_carlo.nim)
138+
{% sample lang="ruby" %}
139+
[import, lang:"ruby"](code/ruby/monte_carlo.rb)
136140
{% endmethod %}
137141

138142

0 commit comments

Comments
 (0)