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; var Counter: Cardinal; Denominator: integer; begin Counter := 0; Denominator := 3; Result := 1; repeat case Odd(Counter) of True: begin Result := Result + (1/Denominator); end; False: begin Result := Result - (1/Denominator); end; end; Inc(Counter); Denominator := Denominator + 2; until Counter >= aIterations ; Result := Result * 4; end;
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.