Chev - 10 months ago 73

C# Question

How might I go about calculating PI in C# to a certain number of decimal places?

I want to be able to pass a number into a method and get back PI calculated to that number of decimal places.

`public decimal CalculatePi(int places)`

{

// magic

return pi;

}

Console.WriteLine(CalculatePi(5)); // Would print 3.14159

Console.WriteLine(CalculatePi(10)); // Would print 3.1415926535

etc...

I don't care about the speed of the program. I just want it to be as simple and easy to understand as it can be. Thanks in advance for the help.

Answer

After much searching I found this little snippet:

```
public static class BigMath
{
// digits = number of digits to calculate;
// iterations = accuracy (higher the number the more accurate it will be and the longer it will take.)
public static BigInteger GetPi(int digits, int iterations)
{
return 16 * ArcTan1OverX(5, digits).ElementAt(iterations)
- 4 * ArcTan1OverX(239, digits).ElementAt(iterations);
}
//arctan(x) = x - x^3/3 + x^5/5 - x^7/7 + x^9/9 - ...
public static IEnumerable<BigInteger> ArcTan1OverX(int x, int digits)
{
var mag = BigInteger.Pow(10, digits);
var sum = BigInteger.Zero;
bool sign = true;
for (int i = 1; true; i += 2)
{
var cur = mag / (BigInteger.Pow(x, i) * i);
if (sign)
{
sum += cur;
}
else
{
sum -= cur;
}
yield return sum;
sign = !sign;
}
}
}
```

It is working like a charm so far. You just have to add the System.Numerics library from the GAC to resolve the BigInteger type.