C#高precision计算 [英] C# high precision calculations
本文介绍了C#高precision计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这个code:
double result = Math.Sqrt(4746073226998689451);
有关结果我得到2178548422,而不是2178548421.999999854etc ......我怎样才能得到更多的precise结果?
For result I get 2178548422 instead of 2178548421.999999854etc... How can I get more precise result?
推荐答案
有关的具体问题,计算平方根,您可以使用十进制类型和牛顿的算法:
For the particular problem, computing the square root, you can use Decimal type and Newton's algorithm:
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);
}
}
结果是:
2178548421.9999998547197773
这篇关于C#高precision计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文