Skip to content
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

Monte carlo crystal #893

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
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
Next Next commit
monte carlo in crystal
henrikac committed Oct 21, 2021
commit 00151dd09d6c7e4efb0bf34e6a5298b3c531d98d
29 changes: 29 additions & 0 deletions contents/monte_carlo_integration/code/crystal/monte_carlo.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Method to determine whether an x, y point is in the unit circle.
def in_circle(x_pos : Float64, y_pos : Float64)
# Setting radius to 1 for unit circle
radius = 1
x_pos ** 2 + y_pos ** 2 < radius ** 2
end

# Method to integrate a unit circle to find pi via monte_carlo
def monte_carlo(n : Int)
pi_count = 0
n.times do
point_x = rand
point_y = rand

if in_circle(point_x, point_y)
pi_count += 1
end
end

# This is using a quarter of the unit sphere in a 1x1 box.
# The formula is pi = (box_length^2 / radius^2) * (pi_count / n), but we
# are only using the upper quadrant and the unit circle, so we can use
# 4*pi_count/n instead
4 * pi_count / n
end

pi_estimate = monte_carlo(10000000)
puts "The pi estimate is: #{pi_estimate}"
puts "Percent error is: #{100 * (pi_estimate - Math::PI).abs / Math::PI} %"
4 changes: 4 additions & 0 deletions contents/monte_carlo_integration/monte_carlo_integration.md
Original file line number Diff line number Diff line change
@@ -101,6 +101,8 @@ each point is tested to see whether it's in the circle or not:
[import:4-9, lang:"coconut"](code/coconut/monte_carlo.coco)
{% sample lang="ps1" %}
[import:1-3, lang:"powershell"](code/powershell/MonteCarlo.ps1)
{% sample lang="crystal" %}
[import:2-6, lang:"crystal"](code/crystal/monte_carlo.cr)
{% endmethod %}

If it's in the circle, we increase an internal count by one, and in the end,
@@ -210,6 +212,8 @@ The code snippets were taken from this [scratch project](https://scratch.mit.edu
[import, lang:"coconut"](code/coconut/monte_carlo.coco)
{% sample lang="ps1" %}
[import, lang:"powershell"](code/powershell/MonteCarlo.ps1)
{% sample lang="crystal" %}
[import, lang:"crystal"](code/crystal/monte_carlo.cr)
{% endmethod %}

<script>