Skip to content

Instantly share code, notes, and snippets.

@mattmanning
Created August 6, 2012 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmanning/3278174 to your computer and use it in GitHub Desktop.
Save mattmanning/3278174 to your computer and use it in GitHub Desktop.
Estimate pi using random points and the distance formula
#!/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