-->

.NET C# Double equivalent System.Numerics.BigInteg

2019-07-25 09:07发布

问题:

I'm am currently writing a program that calculates the digits of pi, and I have a problem. After three iterations the number of correct digits exceeds the memory available in a double.
I heard of the System.Numerics.BigInteger type (in System.Numerics.dll), but I need to use floating point numbers. I do not understand the algorithm well enough to use integers.

It would be great if a version of the BigInteger exists which supports a decimal point. Below I have put my C# code:

var a = 1.0;
var b = 1 / Math.Sqrt(2);
var t = 0.25;
var p = 1.0;
double anext, bnext, tnext, pnext;
int count = 0;

for (int i = 1; i <= accuracy; i++ )
{
            anext = (a + b) / 2;
            bnext = Math.Sqrt(a * b);
            tnext = (t - p * ((a - anext) * (a - anext)));
            pnext = 2 * p;

            a = anext;
            b = bnext;
            t = tnext;
            p = pnext;

            var pi = ((a + b) * (a + b)) / (4 * t);

            Console.WriteLine("Iteration = " + i.ToString());
            Console.WriteLine("Pi =        " + pi + "\n\n\n\n");
}

回答1:

The BigInteger class was written by Melitta Andersen of the BCL team, her first project. It was actually shipped in .NET 3.5 but was hidden, the class was marked internal. Not to become public until .NET 4.0. She also wrote a floating point version, called BigRational. Similar problem, didn't make it into .NET 4.0. These are strange and unexplainable decisions whose reasoning I'm not privy to.

Nevertheless, the source code for BigRational is available. You can download it here.



回答2:

If you're trying to calculate Pi to an arbitrary number of digits of precision, then none of the numeric types available will be valid. You're going to have to use a string (or, preferably, a StringBuilder) and compute the number digit-by-digit.



标签: c# .net pi