C#高精度计算

sve*_*vit 5 .net c# sqrt

考虑以下代码:

double result = Math.Sqrt(4746073226998689451);
Run Code Online (Sandbox Code Playgroud)

结果我得到2178548422而不是2178548421.999999854etc ...我怎样才能得到更精确的结果?

kol*_*kol 7

对于特定问题,计算平方根,可以使用Decimal类型和Newton算法:

using System;

class Program
{
  public static void Main()
  {
    long x = 4746073226998689451;
    decimal sqrt_x = (decimal)Math.Sqrt(x);
    for (int i = 0; i < 10; ++i)
      sqrt_x = 0.5m * (sqrt_x + x / sqrt_x);
    Console.WriteLine("{0:F16}", sqrt_x);
  }
}
Run Code Online (Sandbox Code Playgroud)

结果是:

2178548421.9999998547197773
Run Code Online (Sandbox Code Playgroud)


Ode*_*ded 6

在维基百科上提到了一堆用于.NET的高精度数学库 - Arbitrary-percision artithmatic page.

我之前看过BigNum的推荐,虽然维基百科的链接已经破了,目前我在其他地方找不到这个库.

页面上的另一个选项是MPIRC#绑定.