Computing Pi with Darts – Intro to Java Programming
Articles,  Blog

Computing Pi with Darts – Intro to Java Programming

Let me show you an interesting application of random numbers. You know what pi is. It’s the area of a circle with radius one, and of course, there are formulas for computing pi to any desired precision, but that’s no fun. We’ll compute pi by shooting darts. Specifically, we’ll throw random darts into the square. Most of the time we’ll hit the circle, sometimes we’ll miss, and the ratio of the hits over the tries is going to be approximately the same as the area of the circle, over the area of the square. The square has side lengths 2, so that’s 4, and the area of the circle is of course the desired pi. So how do we do this in Java? We generate a random x between minus 1 and 1. A random y also between minus 1 and 1. Compute the distance from the origin and if that distance was at most 1, then we had a hit. If that distance was larger than 1 then we didn’t have a hit. So go ahead and complete the program that does this. The biggest challenge is to get the x and y to be random values between minus 1 and 1. Because nextDouble gives you values that are between 0 and 1. So you will need to be creative to adjust this range to the one that you want.

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *