这是我当前在 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 类是什么?
感谢您的时间!