-
-
Save anonymous/7b6e1dc5dd2c223a3605d72d287d65a5 to your computer and use it in GitHub Desktop.
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
// 数値解析 ガウスジョルダン法.cpp : コンソール アプリケーションのエントリ ポイントを定義します。 | |
// | |
#include "stdafx.h" | |
#include<iostream> | |
#include<cstdio> | |
#include<cstdlib> | |
#include<cmath> | |
#include<string> | |
#include<algorithm> | |
#include<stack> | |
#include<queue> | |
#include<vector> | |
using namespace std; | |
// ピボット行の選択を行わないガウス・ジョルダンの消去法 | |
void GaussJordan(int n, vector<vector<double> > &a, vector<double> &b) | |
{ | |
double w, pvt; | |
for (int k = 0; k < n; k++) { | |
//ピボット行を順にk行目とする | |
if (a[k][k] == 0.0) { | |
//ピボットが0のときは処理を中断 | |
cout << "pivot==0.0" << endl; | |
exit(1); | |
} | |
//ピボットの値の逆数を計算 | |
pvt = 1.0 / a[k][k]; | |
//対角成分が1になるようにピボット行を正規化 | |
for (int j = k; j < n; j++)a[k][j] = a[k][j] * pvt; | |
b[k] = b[k] * pvt; | |
//ピボット行以外はa[i][k]が0となるようにする | |
for (int i = 0; i < n; i++) { | |
if (i != k) { | |
w = a[i][k]; | |
for (int j = k; j < n; j++) { | |
a[i][j] = a[i][j] - w*a[k][j]; | |
} | |
b[i] = b[i] - w*b[k]; | |
} | |
} | |
//途中結果の表示 | |
for (int i = 0; i < n; i++) { | |
for (int j = 0; j < n; j++) { | |
printf("%23.16e", a[i][j]); | |
cout << endl; | |
} | |
printf("%23.16e", b[i]); | |
cout << endl; | |
} | |
cout << endl; | |
} | |
} | |
int main() | |
{ | |
int n; | |
vector<double> x; | |
//次元の読込 | |
cout << "n="; | |
cin >> n; | |
//n*nの配列aの領域確保 | |
vector<vector<double> > a(n, vector<double>(n)); | |
//n次元配列bの領域確保 | |
vector<double> b(n); | |
//配列aの要素の読込 | |
cout << "配列aの要素の読込" << endl; | |
for (int i = 0; i < n; i++) { | |
for (int j = 0; j < n; j++) { | |
scanf_s("%lf", &a[i][j]); | |
} | |
} | |
//読み込んだ結果の表示 | |
cout << "読み込んだ結果の表示" << endl; | |
for (int i = 0; i < n; i++) { | |
for (int j = 0; j < n; j++) { | |
printf("%lf ",a[i][j]); | |
} | |
cout << endl; | |
} | |
cout << endl; | |
//配列bの要素値の読込 | |
cout << "ベクトルbの要素の読込" << endl; | |
for (int i = 0; i < n; i++)scanf_s("%lf", &b[i]); | |
//読み込んだ結果の表示 | |
for (int i = 0; i < n; i++)printf("%lf", b[i]); | |
cout << endl; | |
//ガウスジョルダンの消去法 | |
GaussJordan(n, a, b); | |
//結果の表示 | |
cout << "x=" << endl; | |
for (int i = 0; i < n; i++)printf("%23.16e ", b[i]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment