.NET C# Double equivalent System.Numerics.BigInteger

点点圈 提交于 2019-12-11 07:35:30

问题


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.



来源:https://stackoverflow.com/questions/5189835/net-c-sharp-double-equivalent-system-numerics-biginteger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!