Created
November 28, 2017 04:40
-
-
Save komasaru/c409099c7d19a0fc5a0f944f7b781990 to your computer and use it in GitHub Desktop.
C++ source code to compute definite integral by Simpson rule.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/********************************************* | |
* シンプソン則による定積分 | |
*********************************************/ | |
#include <iostream> // for cout | |
#include <math.h> // for sqrt | |
#include <stdio.h> // for printf() | |
# define f(x) sqrt(4-x*x) // 被積分関数 | |
using namespace std; | |
/* | |
* 計算クラス | |
*/ | |
class Calc | |
{ | |
// 各種定数 | |
static const int m = 100; // 積分区間分割数 | |
// 各種変数 | |
double h; // 1区間の幅 | |
double x; // X 値 | |
double f_o, f_e; // 奇数項の合計、偶数項の合計 | |
double s; // 面積 | |
int k; // ループインデックス | |
public: | |
// 定積分計算 | |
void calcIntegral(double a, double b); | |
}; | |
/* | |
* 定積分計算 | |
*/ | |
void Calc::calcIntegral(double a, double b) | |
{ | |
// 1区間の幅 | |
h = (b - a) / (2 * m); | |
// 初期化 | |
x = a; // X 値を a で初期化 | |
f_o = 0; // 奇数項の合計 | |
f_e = 0; // 偶数項の合計 | |
s = 0; // 面積初期化 | |
// 奇数項の合計、偶数項の合計計算 | |
for (k = 1; k <= 2*m-2; k++) { | |
x = x + h; | |
if (k % 2 == 1) { | |
f_o = f_o + f(x); | |
} else { | |
f_e = f_e + f(x); | |
} | |
} | |
// 面積計算 | |
s = f(a) + f(b); | |
s += 4 * (f_o + f(b-h)) + 2 * f_e; | |
s *= h / 3; | |
// 結果表示 | |
printf(" /%f\n",b); | |
printf(" | f(x)dx = %f\n", s); | |
printf(" /%f\n",a); | |
} | |
/* | |
* メイン処理 | |
*/ | |
int main() | |
{ | |
// 積分区間 | |
double a, b; | |
try | |
{ | |
// データ入力 | |
cout << "積分区間 A, B :"; | |
scanf("%lf %lf", &a, &b); | |
// 計算クラスインスタンス化 | |
Calc objCalc; | |
// 定積分計算 | |
objCalc.calcIntegral(a, b); | |
} | |
catch (...) { | |
cout << "例外発生!" << endl; | |
return -1; | |
} | |
// 正常終了 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment