Skip to content

Instantly share code, notes, and snippets.

@agilous
Last active September 27, 2023 18:01
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 agilous/e7d9f7be8f3096ddd22040cc4b099e12 to your computer and use it in GitHub Desktop.
Save agilous/e7d9f7be8f3096ddd22040cc4b099e12 to your computer and use it in GitHub Desktop.

Brute Force Pi Calculation

Making use of the observation that Pi is the area of a circle with diameter equal to one, a brute force calculation of Pi would be to:

  1. randomly generate points in a square
  2. count the points within the circle and the total number of points
  3. multiple the ratio of points in the circle to total number of points by the area of a square with a side the length of the diameter of the circle (in this case two (2))

Usage

BruteForcePi.estimate_pi # Estimated value of π: 3.2 (accuracy: 98.1408%)
BruteForcePi.estimate_pi(iterations: 10_000) # Estimated value of π: 3.1164 (accuracy: 99.1981%)
class BruteForcePi
def self.estimate_pi(iterations: 10)
points_in_circle = 0
total_points = 0
iterations.times do
x = rand(-1.0..1.0)
y = rand(-1.0..1.0)
points_in_circle += 1 if Math.sqrt(x**2 + y**2) <= 1
total_points += 1
end
pi = 4.0 * (points_in_circle.to_f / total_points)
accuracy = 100.0 - ((pi - Math::PI).abs / Math::PI * 100.0).round(4)
puts "Estimated value of π: #{pi} (accuracy: #{accuracy}%)"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment