Widgets Calculating Pi

Calculating Pi

By Nick at August 10, 2011 02:36
Filed Under: Delphi

More Stuff I found on my Embarcadero Blog. I believe that my unusual use of the case statement caused a bit of a stir.  I still like using case in this way….

This was fun to write.  I read this interesting post on StackOverflow, which had an answer about asking interview questions, and this was the example he gave:

Given that Pi can be estimated using the function 4 * (1 - 1/3 + 1/5 - 1/7 + …) with more terms giving greater accuracy, write a function that calculates Pi to an accuracy of 5 decimal places.

Now, I don’t get to do much coding anymore, but hey, I’m not completely out of it, so I thought I’d try my hand at it. This is what I came up with:

function CalculatePi(aIterations: Cardinal): Extended;
  Counter: Cardinal;
  Denominator: integer;
  Counter := 0;
  Denominator := 3;
  Result := 1;

    case Odd(Counter) of
      True:  begin
               Result := Result + (1/Denominator);
      False: begin
               Result := Result - (1/Denominator);
    Denominator := Denominator + 2;
  until Counter >= aIterations ;

  Result := Result * 4;

Now, again, I’m no Barry Kelly, and I’m sure that this could be optimized, but I was pretty pleased with that in a ‘that’s what I would have hacked out in an interview" kind of way.  :-)

The more iterations you pass in, the more precise it gets, obviously. I actually didn’t answer the full question (I skipped the precision part), but casual testing shows that about 10,000,000 iterations gets about 5 decimal points of accuracy. In fact, 10,000,000 iteration produces 3.14159275358978, which is pretty accurate.

blog comments powered by Disqus

My Book

A Pithy Quote for You

"No matter how rich you become, how famous or powerful, when you die the size of your funeral will still pretty much depend on the weather."    –  Michael Pritchard

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.