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.
Pi = SUMk=0toinfinity 16-k [ 4/(8k+1) – 2/(8k+4) – 1/(8k+5) – 1/(8k+6) ]. The reason this pi formula is so interesting is because it can be used to calculate the N-th digit of Pi (in base 16) without having to calculate all of the previous digits!
Using Constants in C: In this program the value of π is defined in two different ways. One is by using using the preprocessor directive '#define' to make 'PI' equal to 3.142857. The other uses the key work 'const' to define a double called 'pi' equal to 22.0/7.0.
The mathematical constant pi (π) is the ratio of a circle's circumference to its diameter, and is approximately 3.1415926536. With only these ten decimal places, we could calculate the circumference of Earth to a precision of less than a millimetre.
In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same.
Same algorithm as nicholas but uses yield for lazy evaluation
static public IEnumerable<uint> Pi()
{
uint[] x = new uint[short.MaxValue];
uint[] r = new uint[short.MaxValue];
for (int j = 0; j < short.MaxValue; j++)
x[j] = 20;
for (int i = 0; i < short.MaxValue; i++)
{
uint carry = 0;
for (int j = 0; j < x.Length; j++)
{
uint num = (uint)(x.Length - j - 1);
uint dem = num * 2 + 1;
x[j] += carry;
uint q = x[j] / dem;
r[j] = x[j] % dem;
carry = q * num;
}
yield return (x[x.Length - 1] / 10);
r[x.Length - 1] = x[x.Length - 1] % 10; ;
for (int j = 0; j < x.Length; j++)
{
x[j] = r[j] * 10;
}
}
}
I used short.MaxValue as the upper bound for the number of places but that is because my machine is low on virtual memory. A better machine should be able to accommodate up to int.MaxValue.
The function can be called like so:
class Program
{
static void Main(string[] args)
{
foreach (uint digit in Calculator.Pi().Take(100))
{
Console.WriteLine(digit);
}
Console.Read();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With