-
-
Save xiaolai/2e0624385fad56be3dcf4da057ffd5ee to your computer and use it in GitHub Desktop.
compute pi by Monte-Carlo method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=begin | |
Find pi by the Monte-Carlo method. | |
area of a circle = pi r^2 | |
area of a square = (2r)^2 = 4 r^2 | |
Perform random uniform sampling between -1 and 1. | |
The proportion of points in the unit circle is: | |
p = (pi r^2) / (4r^2) | |
So pi = 4.0 * p | |
=end | |
N = 1000000 | |
n_circle = 0 | |
n_total = 0 | |
N.times do | |
x = rand * 2 - 1 | |
y = rand * 2 - 1 | |
# equation of the unit circle | |
if x ** 2 + y ** 2 < 1 | |
n_circle += 1 | |
end | |
n_total += 1 | |
end | |
puts "pi = #{4.0 * n_circle / n_total}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment