Skip to content

Implement monte carlo in ruby #361

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions contents/monte_carlo_integration/code/ruby/monte_carlo.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
def in_circle(x, y, radius=1)
# Check if coords are in circle via Pythagorean Thm
return (x*x + y*y) < radius*radius
end

def monte_carlo(n_samples, radius=1)
# estimate pi via monte carlo sampling
in_circle_count = 0.0

for _ in 0...n_samples
# randomly choose coords within square
x = rand()*radius
y = rand()*radius
if in_circle(x, y, radius)
in_circle_count += 1
end
end

# circle area is pi*r^2 and rect area is 4r^2
# ratio between the two is then pi/4 so multiply by 4 to get pi
return 4 * (in_circle_count / n_samples)

end


# Main
pi_estimate = monte_carlo(100000)
percent_error = 100 * (pi_estimate - Math::PI).abs / Math::PI

puts "The estimate of pi is: #{pi_estimate.round(3)}"
puts "The percent error is: #{percent_error.round(3)}"

4 changes: 4 additions & 0 deletions contents/monte_carlo_integration/monte_carlo_integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ each point is tested to see whether it's in the circle or not:
[import:23-23, lang:"csharp"](code/csharp/Circle.cs)
{% sample lang="nim" %}
[import:6-7, lang:"nim"](code/nim/monte_carlo.nim)
{% sample lang="ruby" %}
[import:1-4, lang:"ruby"](code/ruby/monte_carlo.rb)
{% endmethod %}

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


Expand Down