这是我目前使用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类吗?
感谢您的时间!
答案 0 :(得分:1)
在比较之前,你不能将你的int转换为BigDecimal吗?
我假设你理解这里的问题是BigDecimal类上接受int的更大,更少等符号没有运算符重载。