Created
December 20, 2017 02:31
-
-
Save komasaru/ac7523e6be4291ea6e462eeaf6fc3981 to your computer and use it in GitHub Desktop.
C++ source code to solve simultaneous equations with Gauss elimination method.
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 <stdio.h> // for printf() | |
// 元の数定義 | |
#define N 4 // 3 | |
using namespace std; | |
/* | |
* 計算クラス | |
*/ | |
class Calc | |
{ | |
double a[N][N + 1]; | |
// 各種変数 | |
double d; // ダミー | |
int i, j, k; // LOOP インデックス | |
public: | |
// 連立方程式を解く(ガウスの消去法) | |
void calcGaussElimination(); | |
}; | |
/* | |
* 連立方程式を解く(ガウスの消去法) | |
*/ | |
void Calc::calcGaussElimination() | |
{ | |
// 係数 | |
static double a[N][N + 1] = { | |
//{ 2.0, -3.0, 1.0, 5.0}, | |
//{ 1.0, 1.0, -1.0, 2.0}, | |
//{ 3.0, 5.0, -7.0, 0.0} | |
{ 1.0, -2.0, 3.0, -4.0, 5.0}, | |
{-2.0, 5.0, 8.0, -3.0, 9.0}, | |
{ 5.0, 4.0, 7.0, 1.0, -1.0}, | |
{ 9.0, 7.0, 3.0, 5.0, 4.0} | |
}; | |
// 元の連立方程式をコンソール出力 | |
for (i = 0; i < N; i++) { | |
for (j = 0; j < N; j++) | |
printf("%+fx%d ", a[i][j], j + 1); | |
printf("= %+f\n", a[i][N]); | |
} | |
// 前進消去 | |
for (k = 0; k < N -1; k++) { | |
for (i = k + 1; i < N; i++) { | |
d = a[i][k] / a[k][k]; | |
for (j = k + 1; j <= N; j++) | |
a[i][j] -= a[k][j] * d; | |
} | |
} | |
// 後退代入 | |
for (i = N - 1; i >= 0; i--) { | |
d = a[i][N]; | |
for (j = i + 1; j < N; j++) | |
d -= a[i][j] * a[j][N]; | |
a[i][N] = d / a[i][i]; | |
} | |
// 結果出力 | |
for (k = 0; k < N; k++) | |
printf("x%d = %f\n", k + 1, a[k][N]); | |
} | |
/* | |
* メイン処理 | |
*/ | |
int main() | |
{ | |
try | |
{ | |
// 計算クラスインスタンス化 | |
Calc objCalc; | |
// 連立方程式を解く(ガウスの消去法) | |
objCalc.calcGaussElimination(); | |
} | |
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