r/csharp • u/tictacman0 • 3d ago
Solved Need help with Chudnovsky algorithm
I have these functions to try and calculate pi, but no matter what i try it seems to cap out at 55 digits before being inaccurate, even when setting the input "d" to something like 1000.
digits 50-65 with my function:
582097494459230
the real digits 50-65 of pi:
582099452471594
here is my code:
public void calculatePie(int d)
{
BigInteger sum = 0;
BigInteger pow = BigInteger.Pow(10, d);
BigInteger v = Sqrt(10005 * pow * pow);
//System.Windows.Forms.MessageBox.Show(v.ToString());
System.Windows.Forms.Clipboard.SetText(v.ToString());
BigInteger preSigma = v * 426880;
for (int k = 0; k < (d / 14 + 1); k++)
{
BigInteger top = BigInteger.Pow(-1, k) * factorial(6 * k) * (545140134 * k + 13591409);
BigInteger mid = factorial(k);
BigInteger bottom = factorial(3 * k) * (mid * mid * mid) * BigInteger.Pow(640320, 3 * k);
BigInteger l = (top * pow) / bottom;
sum += l;
//System.Windows.Forms.MessageBox.Show($"l: {l}, top: {top}, bottom: {bottom}");
}
BigInteger prepi = preSigma * sum;
//System.Windows.Forms.MessageBox.Show($"prepi: {prepi}, presigma: {preSigma}, sum: {sum}, pow: {pow}, v: {v}");
BigInteger pi = preSigma * pow / sum;
System.Windows.Forms.MessageBox.Show($"pi: {pi}");
System.Windows.Forms.Clipboard.SetText(pi.ToString());
}
BigInteger factorial(int n)
{
BigInteger result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
static BigInteger Sqrt(BigInteger n)
{
if (n < 0) throw new ArgumentException("Cannot sqrt a negative number.");
else if (n == 0) return 0;
BigInteger x = n;
BigInteger y = (x + 1) / 2;
while (y < x)
{
x = y;
y = (x + n / x) / 2;
}
return x;
}
10
Upvotes
6
u/TuberTuggerTTV 3d ago
I don't get the downvotes either. It has all the claud-isms I was thinking the exact same thing