グレゴリの級数を用いてπを求める.
積み残しの(情報落ち)影響を調べる.
// これは、アプリケーション ウィザードを使って生成された、VC++ アプリケーション プロジェクトの
// メイン プロジェクト ファイルです。
#include "stdafx.h"
#using <mscorlib.dll>
#include "iostream"
#include <iomanip>
#include <cmath>
using namespace std;
using namespace System;
//グレゴリの級数でπを求める
void calcpai(int N);
void calcpai2(int N);
double odd(int n);
//π = 3.14159 26535 89793
int _tmain()
{
// TODO: 下のサンプル コードを独自のコードに置き換えてください。
//Console::WriteLine(S"Hello World");
cout << "真値:3.14159 26535 89793" << endl;
cout << "N:\t\t" << "float\t\t" << "double\t\t" << "long double" << endl;
for(int i = 10;i <= 10000000 ;i *= 10){
calcpai(i);
}
cout << endl << endl;
for(int i = 10;i <= 10000000 ;i *= 10){
calcpai2(i);
}
return 0;
}
//グレゴリの級数でπを求める
void calcpai(int N){
float fpai = 0.0;
double dpai = 0.0;
long double ldpai = 0.0;
for(int i = 0;i < N;i++){
fpai += (float)((odd(i) / (2 * i + 1)) * 4); //Σ(((-1)^n)*(1/(2n+1)))
dpai += (odd(i) / (2 * i + 1) )* 4;
ldpai += (odd(i) / (2 * i + 1) )* 4;
}
cout << setw(8) << i << "\t" << setprecision(10) << fpai << "\t" << dpai << "\t" << ldpai << endl;
}
//情報落ちを防ぐ
void calcpai2(int N){
float fpai = 0.0;
double dpai = 0.0;
long double ldpai = 0.0;
for(int i = N -1;i >= 0;i--){
fpai += (float)((odd(i) / (2 * i + 1)) * 4.0); //Σ(((-1)^n)*(1/(2n+1)))
dpai += (odd(i) / (2 * i + 1) )* 4.0;
ldpai += (odd(i) / (2 * i + 1) )* 4.0;
}
cout << setw(8) << N << "\t" << setprecision(10) << fpai << "\t" << dpai << "\t" << ldpai << endl;
}
double odd(int n){
return (n % 2)? -1.0 :1.0;
}