Created
August 6, 2012 20:30
-
-
Save mattmanning/3278174 to your computer and use it in GitHub Desktop.
Estimate pi using random points and the distance formula
This file contains 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
#!/usr/bin/env ruby | |
# | |
# Estimate pi using 1 random point: | |
# ./pi.rb 1 | |
# | |
# Estimate pi using 1000 random points: | |
# ./pi.rb 1000 | |
class Point | |
def initialize | |
@x = rand | |
@y = rand | |
end | |
def inside? | |
Math.sqrt(@x**2 + @y**2) < 1 | |
end | |
end | |
count = ARGV.shift.to_i | |
sum = 0 | |
count.times do | |
sum += 1 if Point.new.inside? | |
end | |
puts (sum.to_f / count) * 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment