Approximate Pi With Random Numbers
I came across some old computer science notes about using random numbers to calculate π and I thought it would be fun to code it up really quick in Ruby. First, however, I think it needs a bit of explanation. Let's start with a square with sides of length 1. Next, let's circumscribe a quarter circle within that square (making the radius of the circle 1). Let's also assume that the bottom left corner of the square is at the origin (0, 0). (I've included a--very simple--diagram in the way of illustration). We know that the area of the square is r2 or 12 or 1. We know that the area of the quarter circle is πr2/4 or π/4. (Notice that the r has dropped out.)
Now for the second part. Let's take a random number generator that generates random numbers between 0 and 1 (not so hard in computer science). A pair of them (xr, yr) will fall somewhere within our square. Using the distance formula, we can see if the random pair also falls within the circle (the square root of x2 + y2). We choose some total number of random coordinates and see how many fall within the circle compared to the total number (which all fall within the square). Using the ratio of the number within the square to the number within the circle we can take a guess at the value of π.
Here's the code:
1 2 3 4 5 |
print "Number of iterations: " iterations = gets.chomp.to_i count = 0 iterations.times { count += 1 if (rand**2 + rand**2)**0.5 < 1 } puts 4.0*count.to_f/iterations.to_f |
The more iterations that you do, the closer to π you get.





