Skip to content

Instantly share code, notes, and snippets.

@woodRock
Created August 28, 2018 12:18
Show Gist options
  • Save woodRock/27a9c125a093ecfb49b72e44232504ae to your computer and use it in GitHub Desktop.
Save woodRock/27a9c125a093ecfb49b72e44232504ae to your computer and use it in GitHub Desktop.
The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method. Hint: The basic equation of a circle is x2 + y2 = r2.
#!/usr/bin/env ruby
def pi_estimation(r=5)
inside =0.0
outside = 0.0
total = 0.0
rnd = Random.new
for i in 1 ... 10000
x = rnd.rand(-1*inside..inside)
y = rnd.rand(-1*inside..inside)
measure = distance(x, y)
if measure > inside
outside += 1
else
inside += 1
end
end
total = outside + inside
return (4 * (inside / total)).to_f()
end
def distance(x1, y1, x=0, y=0)
x_diff = x1 - x
y_diff = y1 - y
x_diff *= x_diff
y_diff *= y_diff
return Math.sqrt(x_diff + y_diff)
end
puts '%.2f' % pi_estimation()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment