<p>How can I calculate the value of PI using C#?</p>

<p>I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?</p>

<p>I'm not too fussy about performance, mainly how to go about it from a learning point of view.</p>

[{'answer_id': 39401, 'author': 'Niyaz', 'author_id': 184, 'author_profile': 'https://Stackoverflow.com/users/184', 'pm_score': 1, 'selected': False, 'text': '<p>Calculate like this:</p>\n\n<pre><code>x = 1 - 1/3 + 1/5 - 1/7 + 1/9  (... etc as far as possible.)\nPI = x * 4\n</code></pre>\n\n<p>You have got Pi !!!</p>\n\n<p>This is the simplest method I know of.</p>\n\n<p>The value of PI slowly converges to the actual value of Pi (3.141592165......). If you iterate more times, the better.</p>\n'}, {'answer_id': 39404, 'author': 'wvdschel', 'author_id': 2018, 'author_profile': 'https://Stackoverflow.com/users/2018', 'pm_score': 7, 'selected': True, 'text': '<p>If you want recursion:</p>\n\n<pre><code>PI = 2 * (1 + 1/3 * (1 + 2/5 * (1 + 3/7 * (...))))\n</code></pre>\n\n<p>This would become, after some rewriting:</p>\n\n<pre><code>PI = 2 * F(1);\n</code></pre>\n\n<p>with F(i):</p>\n\n<pre><code>double F (int i) {\n    return 1 + i / (2.0 * i + 1) * F(i + 1);\n}\n</code></pre>\n\n<p>Isaac Newton (you may have heard of him before ;) ) came up with this trick.\nNote that I left out the end condition, to keep it simple. In real life, you kind of need one.</p>\n'}, {'answer_id': 39424, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 5, 'selected': False, 'text': '<p>How about using:</p>\n\n<pre><code>double pi = Math.PI;\n</code></pre>\n\n<p>If you want better precision than that, you will need to use an algorithmic system and the Decimal type.</p>\n'}, {'answer_id': 39442, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 0, 'selected': False, 'text': "<p>In any production scenario, I would compel you to look up the value, to the desired number of decimal points, and store it as a 'const' somewhere your classes can get to it.</p>\n\n<p>(unless you're writing scientific 'Pi' specific software...)</p>\n"}, {'answer_id': 39491, 'author': 'OysterD', 'author_id': 2638, 'author_profile': 'https://Stackoverflow.com/users/2638', 'pm_score': 2, 'selected': False, 'text': '<p>Good overview of different algorithms:</p>\n\n<ul>\n<li><a href="http://en.wikipedia.org/wiki/Computing_%CF%80" rel="nofollow noreferrer">Computing pi</a>;</li>\n<li><a href="http://en.wikipedia.org/wiki/Gauss%E2%80%93Legendre_algorithm" rel="nofollow noreferrer">Gauss-Legendre-Salamin</a>.</li>\n</ul>\n\n<p>I\'m not sure about the complexity claimed for the Gauss-Legendre-Salamin algorithm in the first link (I\'d say O(N log^2(N) log(log(N)))).</p>\n\n<p>I do encourage you to try it, though, the convergence is <em>really</em> fast.</p>\n\n<p>Also, I\'m not really sure about why trying to convert a quite simple procedural algorithm into a recursive one?</p>\n\n<p>Note that if you are interested in performance, then working at a bounded precision (typically, requiring a \'double\', \'float\',... output) does not really make sense, as the obvious answer in such a case is just to hardcode the value.</p>\n'}, {'answer_id': 39497, 'author': 'DrPizza', 'author_id': 2131, 'author_profile': 'https://Stackoverflow.com/users/2131', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public double PI = 22.0 / 7.0;\n</code></pre>\n'}, {'answer_id': 39566, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 0, 'selected': False, 'text': "<p>Regarding...</p>\n\n<blockquote>\n  <p>... how to go about it from a learning point of view.</p>\n</blockquote>\n\n<p>Are you trying to learning to program scientific methods? or to produce production software? I hope the community sees this as a valid question and not a nitpick.</p>\n\n<p>In either case, I think writing your own Pi is a solved problem. Dmitry showed the 'Math.PI' constant already. Attack another problem in the same space! Go for generic Newton approximations or something slick.</p>\n"}, {'answer_id': 39579, 'author': 'joel.neely', 'author_id': 3525, 'author_profile': 'https://Stackoverflow.com/users/3525', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s a nice approach (from <a href="http://en.wikipedia.org/wiki/Pi" rel="nofollow noreferrer">the main Wikipedia entry on pi</a>); it converges much faster than the simple formula discussed above, and is quite amenable to a recursive solution if your intent is to pursue recursion as a learning exercise.  (Assuming that you\'re after the learning experience, I\'m not giving any actual code.)</p>\n\n<p>The underlying formula is the same as above, but this approach averages the partial sums to accelerate the convergence.</p>\n\n<p>Define a two parameter function, pie(h, w), such that:</p>\n\n<pre><code>pie(0,1) = 4/1\npie(0,2) = 4/1 - 4/3\npie(0,3) = 4/1 - 4/3 + 4/5\npie(0,4) = 4/1 - 4/3 + 4/5 - 4/7\n... and so on\n</code></pre>\n\n<p>So your first opportunity to explore recursion is to code that "horizontal" computation as the "width" parameter increases (for "height" of zero).</p>\n\n<p>Then add the second dimension with this formula:</p>\n\n<pre><code>pie(h, w) = (pie(h-1,w) + pie(h-1,w+1)) / 2\n</code></pre>\n\n<p>which is used, of course, only for values of h greater than zero.</p>\n\n<p>The nice thing about this algorithm is that you can easily mock it up with a spreadsheet to check your code as you explore the results produced by progressively larger parameters. By the time you compute pie(10,10), you\'ll have an approximate value for pi that\'s good enough for most engineering purposes.</p>\n'}, {'answer_id': 40572, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>What is PI? The circumference of a circle divided by its diameter.</p>\n\n<p>In computer graphics you can plot/draw a circle with its centre at 0,0 from a initial point x,y, the next point x',y' can be found using a simple formula:\nx' = x + y / h : y' = y - x' / h</p>\n\n<p>h is usually a power of 2 so that the divide can be done easily with a shift (or subtracting from the exponent on a double). h also wants to be the radius r of your circle. An easy start point would be x = r, y = 0, and then to count c the number of steps until x &lt;= 0 to plot a quater of a circle. PI is 4 * c / r or PI is 4 * c / h</p>\n\n<p>Recursion to any great depth, is usually impractical for a commercial program, but tail recursion allows an algorithm to be expressed recursively, while implemented as a loop. Recursive search algorithms can sometimes be implemented using a queue rather than the process's stack, the search has to backtrack from a deadend and take another path - these backtrack points can be put in a queue, and multiple processes can un-queue the points and try other paths.</p>\n"}, {'answer_id': 40657, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>There are a couple of really, really old tricks I'm surprised to not see here.</p>\n\n<p>atan(1) == PI/4, so an old chestnut when a trustworthy arc-tangent function is\npresent is 4*atan(1).</p>\n\n<p>A very cute, fixed-ratio estimate that makes the old Western 22/7 look like dirt\nis 355/113, which is good to several decimal places (at least three or four, I think).\nIn some cases, this is even good enough for integer arithmetic:  multiply by 355 then divide by 113.</p>\n\n<p>355/113 is also easy to commit to memory (for some people anyway):  count one, one, three, three, five, five and remember that you're naming the digits in the denominator and numerator (if you forget which triplet goes on top, a microsecond's thought is usually going to straighten it out).</p>\n\n<p>Note that 22/7 gives you:  3.14285714, which is wrong at the thousandths.</p>\n\n<p>355/113 gives you 3.14159292 which isn't wrong until the ten-millionths.</p>\n\n<p>Acc. to /usr/include/math.h on my box, M_PI is #define'd as:\n   3.14159265358979323846\nwhich is probably good out as far as it goes.</p>\n\n<p>The lesson you get from estimating PI is that there are lots of ways of doing it,\nnone will ever be perfect, and you have to sort them out by intended use.</p>\n\n<p>355/113 is an old Chinese estimate, and I believe it pre-dates 22/7 by many years.  It was taught me by a physics professor when I was an undergrad.</p>\n"}, {'answer_id': 40690, 'author': 'OysterD', 'author_id': 2638, 'author_profile': 'https://Stackoverflow.com/users/2638', 'pm_score': 0, 'selected': False, 'text': '<p>@Thomas Kammeyer:</p>\n\n<p>Note that Atan(1.0) is quite often hardcoded, so 4*Atan(1.0) is not really an \'algorithm\' if you\'re calling a library Atan function (an quite a few already suggested indeed proceed by replacing Atan(x) by a series (or infinite product) for it, then evaluating it at x=1.</p>\n\n<p>Also, <strong>there are very few cases where you\'d need pi at more precision than a few tens of bits</strong> (which can be easily hardcoded!). I\'ve worked on applications in mathematics where, to compute some (quite complicated) mathematical objects (which were polynomial with integer coefficients), I had to do arithmetic on real and complex numbers (including computing pi) with a precision of up to a few million bits... but this is not very frequent \'in real life\' :)</p>\n\n<p>You can look up the following example <a href="http://gmplib.org/pi-with-gmp.html" rel="nofollow noreferrer">code</a>.</p>\n'}, {'answer_id': 4104365, 'author': 'Dean Chalk', 'author_id': 498104, 'author_profile': 'https://Stackoverflow.com/users/498104', 'pm_score': 1, 'selected': False, 'text': '<pre><code>Enumerable.Range(0, 100000000).Aggregate(0d, (tot, next) =&gt; tot += Math.Pow(-1d, next)/(2*next + 1)*4)\n</code></pre>\n'}, {'answer_id': 4283808, 'author': 'Oliver', 'author_id': 1838048, 'author_profile': 'https://Stackoverflow.com/users/1838048', 'pm_score': 3, 'selected': False, 'text': '<p>If you take a close look into this really good guide:</p>\n\n<p><a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=86b3d32b-ad26-4bb8-a3ae-c1637026c3ee&amp;displaylang=en" rel="nofollow">Patterns for Parallel Programming: Understanding and Applying Parallel Patterns with the .NET Framework 4</a></p>\n\n<p>You\'ll find at Page 70 this cute implementation (with minor changes from my side):</p>\n\n<pre><code>static decimal ParallelPartitionerPi(int steps)\n{\n    decimal sum = 0.0;\n    decimal step = 1.0 / (decimal)steps;\n    object obj = new object();\n\n    Parallel.ForEach(\n        Partitioner.Create(0, steps),\n        () =&gt; 0.0,\n        (range, state, partial) =&gt;\n        {\n            for (int i = range.Item1; i &lt; range.Item2; i++)\n            {\n                decimal x = (i - 0.5) * step;\n                partial += 4.0 / (1.0 + x * x);\n            }\n\n            return partial;\n        },\n        partial =&gt; { lock (obj) sum += partial; });\n\n    return step * sum;\n}\n</code></pre>\n'}, {'answer_id': 6650877, 'author': 'Rodrigo', 'author_id': 838981, 'author_profile': 'https://Stackoverflow.com/users/838981', 'pm_score': 0, 'selected': False, 'text': '<p>The following link shows how to calculate the pi constant based on its definition as an integral, that can be written as a limit of a summation, it\'s very interesting:\n<a href="https://sites.google.com/site/rcorcs/posts/calculatingthepiconstant" rel="nofollow">https://sites.google.com/site/rcorcs/posts/calculatingthepiconstant</a>\nThe file "Pi as an integral" explains this method used in this post.</p>\n'}, {'answer_id': 11075542, 'author': 'Tim Long', 'author_id': 98516, 'author_profile': 'https://Stackoverflow.com/users/98516', 'pm_score': 0, 'selected': False, 'text': '<p>I like <a href="http://www.cygnus-software.com/misc/pidigits.htm" rel="nofollow">this paper</a>, which explains how to calculate π based on a Taylor series expansion for Arctangent.</p>\n\n<p>The paper starts with the simple assumption that</p>\n\n<blockquote>\n  <p>Atan(1) = π/4 radians</p>\n</blockquote>\n\n<p>Atan(x) can be iteratively estimated with the Taylor series</p>\n\n<blockquote>\n  <p>atan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9...</p>\n</blockquote>\n\n<p>The paper points out why this is not particularly efficient and goes on to make a number of logical refinements in the technique. They also provide a sample program that computes π to a few thousand digits, complete with source code, including the infinite-precision math routines required.</p>\n'}, {'answer_id': 25638402, 'author': 'ronalt MkDonalt', 'author_id': 4002951, 'author_profile': 'https://Stackoverflow.com/users/4002951', 'pm_score': 1, 'selected': False, 'text': '<pre><code>using System;\n\nnamespace Strings\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n\n/*          decimal pie = 1; \n            decimal e = -1;\n*/\n            var stopwatch = new System.Diagnostics.Stopwatch();\n            stopwatch.Start(); //added this nice stopwatch start routine \n\n  //leibniz formula in C# - code written completely by Todd Mandell 2014\n/*\n            for (decimal f = (e += 2); f &lt; 1000001; f++)\n            {\n                 e += 2;\n                 pie -= 1 / e;\n                 e += 2;\n                 pie += 1 / e;\n                 Console.WriteLine(pie * 4);\n            }\n\n                 decimal finalDisplayString = (pie * 4);\n                 Console.WriteLine("pie = {0}", finalDisplayString);\n                 Console.WriteLine("Accuracy resulting from approximately {0} steps", e/4); \n*/\n\n// Nilakantha formula - code written completely by Todd Mandell 2014\n// π = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + 4/(10*11*12) - (4/(12*13*14) etc\n\n            decimal pie = 0;\n            decimal a = 2;\n            decimal b = 3;\n            decimal c = 4;\n            decimal e = 1;\n\n            for (decimal f = (e += 1); f &lt; 100000; f++) \n            // Increase f where "f &lt; 100000" to increase number of steps\n            {\n\n                pie += 4 / (a * b * c);\n\n                a += 2;\n                b += 2;\n                c += 2;\n\n                pie -= 4 / (a * b * c);\n\n                a += 2;\n                b += 2;\n                c += 2;\n\n                e += 1;\n            }\n\n            decimal finalDisplayString = (pie + 3);\n            Console.WriteLine("pie = {0}", finalDisplayString);\n            Console.WriteLine("Accuracy resulting from {0} steps", e); \n\n            stopwatch.Stop();\n            TimeSpan ts = stopwatch.Elapsed;\n            Console.WriteLine("Calc Time {0}", ts); \n\n            Console.ReadLine();\n\n         }\n     }\n }\n</code></pre>\n'}, {'answer_id': 26697642, 'author': 'Curious', 'author_id': 2610539, 'author_profile': 'https://Stackoverflow.com/users/2610539', 'pm_score': 1, 'selected': False, 'text': '<pre><code>    public static string PiNumberFinder(int digitNumber)\n    {\n        string piNumber = "3,";\n        int dividedBy = 11080585;\n        int divisor = 78256779;\n        int result;\n\n        for (int i = 0; i &lt; digitNumber; i++)\n        {\n            if (dividedBy &lt; divisor)\n                dividedBy *= 10;\n\n            result = dividedBy / divisor;\n\n            string resultString = result.ToString();\n            piNumber += resultString;\n\n            dividedBy = dividedBy - divisor * result;\n        }\n\n        return piNumber;\n    }\n</code></pre>\n'}, {'answer_id': 40686034, 'author': 'Larry Paden', 'author_id': 7175676, 'author_profile': 'https://Stackoverflow.com/users/7175676', 'pm_score': 0, 'selected': False, 'text': '<p>First, note that C# can use the Math.PI field of the .NET framework:  </p>\n\n<p><a href="https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/system.math.pi(v=vs.110).aspx</a></p>\n\n<p>The nice feature here is that it\'s a full-precision double that you can either use, or compare with computed results.  The tabs at that URL have similar constants for C++, F# and Visual Basic.  </p>\n\n<p>To calculate more places, you can write your own extended-precision code.  One that is quick to code and reasonably fast and easy to program is: </p>\n\n<p>Pi = 4 * [4 * arctan (1/5) - arctan (1/239)]</p>\n\n<p>This formula and many others, including some that converge at amazingly fast rates, such as 50 digits per term, are at Wolfram:  </p>\n\n<p><a href="http://mathworld.wolfram.com/PiFormulas.html" rel="nofollow noreferrer">Wolfram Pi Formulas</a></p>\n'}, {'answer_id': 49317760, 'author': 'Slaven Tojić', 'author_id': 7308680, 'author_profile': 'https://Stackoverflow.com/users/7308680', 'pm_score': 0, 'selected': False, 'text': '<p><strong>PI (π)</strong> can be calculated by using <strong>infinite series</strong>. Here are two examples:</p>\n\n<p><strong>Gregory-Leibniz Series:</strong></p>\n\n<blockquote>\n  <p>π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...</p>\n</blockquote>\n\n<p>C# method :</p>\n\n<pre><code>public static decimal GregoryLeibnizGetPI(int n)\n{\n    decimal sum = 0;\n    decimal temp = 0;\n    for (int i = 0; i &lt; n; i++)\n    {\n        temp = 4m / (1 + 2 * i);\n        sum += i % 2 == 0 ? temp : -temp;\n    }\n    return sum;\n}\n</code></pre>\n\n<p><strong>Nilakantha Series:</strong></p>\n\n<blockquote>\n  <p>π = 3 + 4 / (2x3x4) - 4 / (4x5x6) + 4 / (6x7x8) - 4 / (8x9x10) + ...</p>\n</blockquote>\n\n<p>C# method:</p>\n\n<pre><code>public static decimal NilakanthaGetPI(int n)\n{\n    decimal sum = 0;\n    decimal temp = 0;\n    decimal a = 2, b = 3, c = 4;\n    for (int i = 0; i &lt; n; i++)\n    {\n        temp = 4 / (a * b * c);\n        sum += i % 2 == 0 ? temp : -temp;\n        a += 2; b += 2; c += 2;\n    }\n    return 3 + sum;\n}\n</code></pre>\n\n<p>The input parameter <code>n</code> for both functions represents the number of iteration.</p>\n\n<p>The Nilakantha Series in comparison with Gregory-Leibniz Series converges more quickly. The methods can be tested with the following code:</p>\n\n<pre><code>static void Main(string[] args)\n{\n    const decimal pi = 3.1415926535897932384626433832m;\n    Console.WriteLine($"PI = {pi}");\n\n    //Nilakantha Series\n    int iterationsN = 100;\n    decimal nilakanthaPI = NilakanthaGetPI(iterationsN);\n    decimal CalcErrorNilakantha = pi - nilakanthaPI;\n    Console.WriteLine($"\\nNilakantha Series -&gt; PI = {nilakanthaPI}");\n    Console.WriteLine($"Calculation error = {CalcErrorNilakantha}");\n    int numDecNilakantha = pi.ToString().Zip(nilakanthaPI.ToString(), (x, y) =&gt; x == y).TakeWhile(x =&gt; x).Count() - 2;\n    Console.WriteLine($"Number of correct decimals = {numDecNilakantha}");\n    Console.WriteLine($"Number of iterations = {iterationsN}");\n\n    //Gregory-Leibniz Series\n    int iterationsGL = 1000000;\n    decimal GregoryLeibnizPI = GregoryLeibnizGetPI(iterationsGL);\n    decimal CalcErrorGregoryLeibniz = pi - GregoryLeibnizPI;\n    Console.WriteLine($"\\nGregory-Leibniz Series -&gt; PI = {GregoryLeibnizPI}");\n    Console.WriteLine($"Calculation error = {CalcErrorGregoryLeibniz}");\n    int numDecGregoryLeibniz = pi.ToString().Zip(GregoryLeibnizPI.ToString(), (x, y) =&gt; x == y).TakeWhile(x =&gt; x).Count() - 2;\n    Console.WriteLine($"Number of correct decimals = {numDecGregoryLeibniz}");\n    Console.WriteLine($"Number of iterations = {iterationsGL}");\n\n    Console.ReadKey();\n}\n</code></pre>\n\n<p>The following output shows that Nilakantha Series returns six correct decimals of PI with one hundred iterations whereas Gregory-Leibniz Series returns five correct decimals of PI with one million iterations:</p>\n\n<p><a href="https://i.stack.imgur.com/lXZhT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lXZhT.png" alt="enter image description here"></a></p>\n\n<p>My code can be tested >> <a href="https://dotnetfiddle.net/Et4rAX" rel="nofollow noreferrer">here</a></p>\n'}, {'answer_id': 50304341, 'author': 'Idan Rotbart', 'author_id': 6941443, 'author_profile': 'https://Stackoverflow.com/users/6941443', 'pm_score': 0, 'selected': False, 'text': '<p>Here is a nice way:\nCalculate a series of 1/x^2 for x from 1 to what ever you want- the bigger number- the better pie result. Multiply the result by 6 and to sqrt().\nHere is the code in c# (main only):</p>\n\n<pre><code>static void Main(string[] args)\n    {\n        double counter = 0;\n        for (double i = 1; i &lt; 1000000; i++)\n        {\n\n            counter = counter + (1 / (Math.Pow(i, 2)));\n\n        }\n        counter = counter * 6;\n        counter = Math.Sqrt(counter);\n        Console.WriteLine(counter);\n    }\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/39395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/383/']