4
因此,這裏是根據楚德諾夫斯基算法計算PI一些C++代碼:與楚德諾夫斯基算法計算PI數
#include <iostream>
#include <cmath>
#include <iomanip>
int fact(int digit)
{
int result = 1;
for (int i=digit; i>1; i--)
{
result *= i;
}
return result;
}
int main()
{
long double pi = 0.0;
int precision = 10;
for (int k=0; k<=precision; k++)
{
pi += (pow(-1, k)*fact((6*k))*(13591409+545140134*k))/(fact(3*k)*pow(fact(k),3)*pow(640320, (3*k+1.5)));
}
pi = 1.0/(12*pi);
std::cout<<std::setprecision(80)<<pi<<'\n'<<M_PI<<'\n';
}
的問題是,此代碼僅返回15的PI編號右位,它的另一部分是垃圾...當精度變量設置爲12或更大時,它返回-nan。有人可以幫我嗎? TIA
編輯:Ubuntu 12.10 x64,gcc 4.7.2
在需要雙精度字符而不是整數字面量的地方使用雙字面量。 '13591409 + 545140134 * k'應該是'13591409.0 + 545140134.0 * k',否則可能會發生整數溢出。 – 2013-02-10 12:20:10
您的因子例程很快溢出。 – 2013-02-10 12:21:06
thanx,我已經修復了它,但沒有任何更改... – 2013-02-10 12:23:51