c# - C# 中小数的任意精度帮助?

标签 c# math pi arbitrary-precision

这是我当前在 C# 中使用 chudnovsky 方法计算 Pi 的代码:

using System;
using System.Diagnostics;
using System.IO;
using java.math;

namespace pi.chudnovsky
{
    public class Program
    {
        static Double Factorial(Double fact)
        {
            //begin factorial function
            if (fact <= 1)
                return 1;
            else
                return fact * Factorial(fact - 1); //loops multiplication until the factorial is reached
        }
        static Double doSummation(Double maxPower)
        {
            //begin chudnovsky summation function
            Double sum = 0;
            for (int i = 0; i <= maxPower; i++) //starts at i=0
            {
                sum += ((Math.Pow(-1, i)) * Factorial(6 * i) * (13591409 + 5451401 * i)) / (Factorial(3 * i) * Factorial(i) * Factorial(i) * Factorial(i) * Math.Pow(640320, (3 * i + 1.5))); //chudnovsky algorithm
            }
            return sum;
        }
        static void Main(string[] args)
        {
            int num;
            Console.WriteLine("Enter how many terms to compute Chudnovsky summation: ");
            //begin stopwatch
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            //parse user input
            num = Convert.ToInt32(Console.ReadLine());
            //perform calculation
            Double inv = 1 / (12 * doSummation(num));
            //stop stopwatch
            stopwatch.Stop();
            //display info
            Console.WriteLine(inv);
            Console.WriteLine("3.14159265358979323846264338327950288419716939937510");
            Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed.TotalMilliseconds);
            //write to pi.txt
            TextWriter pi = new StreamWriter("pi.txt");
            pi.WriteLine(inv);
            pi.Close();
            //write to stats.txt
            TextWriter stats = new StreamWriter("stats.txt");
            stats.WriteLine(stopwatch.Elapsed.TotalMilliseconds);
            stats.Close();
        }
    }
}

因此,我包含了 J# 库,并包含了 java.math。现在,当我用“BigDecimal”替换所有“double”时,出现以下编译错误:

http://f.cl.ly/items/1r2X26470d0d0n260p0p/Image%202011-11-14%20at%206.16.19%20PM.png

我知道这不是我在循环中使用 Int 的问题,因为它与 Doubles 完美配合。我的问题是,您如何解决与 int 和 BigDecimal 相关的这些错误,或者您可以推荐另一个任意精度的库吗?

我试过使用 XMPIR,已经得到了所有要编译的东西,但我得到:

http://f.cl.ly/items/1l3C371j2u3z3n2g3a0j/Image%202011-11-14%20at%206.20.24%20PM.png

所以我可以使用 p/invoke 来包含 xmpir,这样我就可以使用任何 bigdecimal 类吗?

感谢您的宝贵时间!

最佳答案

在比较它们之前,您不能将 int 转换为 BigDecimal 吗?

我假设您理解这里的问题是,在接受 int 的 BigDecimal 类上没有用于大于、小于等符号的运算符重载。

关于c# - C# 中小数的任意精度帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130392/

相关文章:

c# - 散列对象集 C#

c# - Microsoft.VisualStudio.TestTools.UnitTesting 给出错误

c# - 如何在C Sharp中使用DLL

用级数计算 pi

Scala BigDecimal 如何显示更多小数?

c# - 我是否需要检查目录/文件是否存在?

c++ - 如何在C++中计算数字的第3个根

math - 查找偏差/元素列表的标准偏差

android - 十进制数学错误结果

java - 以 sig 数字精度计算 PI,无需舍入