Everyone loves π! I was bored today, so obviously I got the urge to make a program to calculate it. (Who doesn’t, right?) A friend of mine has hacked one together in Java, but I feel the need to show him how it’s done in C#. There’s nothing wrong with a little healthy competition after all. Bring it on!
The first challenge was to figure out how to calculate π. I came up with this website. I decided to use “Gregory’s Formula” at the bottom of the page, which is an alternating series.
Here’s what I saw on the website:
So that means that…
The last equation is just the calculus version of the first one. In either way the basic pattern is that I start with 1/1, subtract 1/3, add 1/5, and so on. Then at whatever point I want multiply that resulting summation by 4 to get an approximation of π. The fun part is translating that into code.
So what does that look like in code? Well, I made a whole PiCalculator class, but this is the part that runs over and over:
And whenever Pi is requested, it just multiplies aFourh by 4.
That’s the basic idea. There’s more code to initiate the calculation process (and run it on a separate thread), a bunch of accessors so that the main program can get information to display, and finally there’s code to actually display all of the information.
When the program is first opened it looks like this:
It’s calculating π in the background, but for performance sake it only shows the user the values when the “Update” button or enter is pressed.
After 30 seconds it has more pi than any sane person would care about.
One thing I had to look out for was numbers that were too extreme. Eventually that fraction that is being added and subtracted in the summation is going to be rounded to zero, so I account for that in the code, stopping the calculations in that event. As you can see, though, even with my computer’s Intel Core 2 Quad Q660, I would have to run this program for several years to have that happen.
So this was a fun little project. Feel free to try it out for yourself!
Download the executable here
Download the C# source code here