Skip to content

Instantly share code, notes, and snippets.

@programmerextraordinaire
Last active August 9, 2018 17:52
Show Gist options
  • Save programmerextraordinaire/3ea13d0b3e7952ca02e3ee63bf9f873f to your computer and use it in GitHub Desktop.
Save programmerextraordinaire/3ea13d0b3e7952ca02e3ee63bf9f873f to your computer and use it in GitHub Desktop.
From a StackOverflow question about estimating Pi. Answered in LinqPad.
// From: http://stackoverflow.com/questions/406760/whats-your-most-controversial-programming-opinion
// Given that Pi can be estimated using the function 4 * (1 - 1/3 + 1/5 - 1/7 + ...)
// write a function that calculates Pi to an accuracy of 5 decimal places.
var oddFractions = new List<double>();
var pi = 4.0;
// Fill the oddFractions list until we have 5 decimal places of accuracy.
for (int i = 1, j = 1; j < 1000000; i++, j+=2)
{
var frac = 1.0 / j;
if ((i % 2) == 0)
frac = -frac;
oddFractions.Add(frac);
// Test to see if we're done. Only look at every 10K.
if ((i % 10000) == 0)
{
pi = oddFractions.Sum()*4;
Console.WriteLine("{0}. {1}", i, pi);
if ((Math.PI - pi) < 0.000001)
break;
}
}
pi.Dump(); // Output: 3.14159065358969
Math.PI.Dump(); // Output: 3.14159265358979
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment