2019-01-29 21:11:15 UNSELECTED

ピボット選択付きガウス消去法

Copy Copied! Full
#include<iostream> #include<cmath> using namespace std; #define n 4 int main() { double a[n + 1][n + 1] = {{0, 0, 0, 0, 0}, {0, 2, 4, 1, -3}, {0, -1, -2, 2, 4}, {0, 4, 2, -3, 5}, {0, 5, -4, -3, 1}}; double b[n + 1][1] = {{0}, {0}, {10}, {2}, {6}}; for (int i = 1; i < n; ++i) { //aii //select pibot double max = abs(a[i][i]); int key = i; for (int j = i + 1; j <= n; ++j) { if (max < abs(a[j][i])) { max = abs(a[j][i]); key = j; } } if (max < 0.001) { cout << "no" << endl; return 0; } if (key != i) { for (int j = 1; j <= n; ++j) { swap(a[i][j], a[key][j]); } swap(b[i][0], b[key][0]); //これ忘れて時間かかりすぎた } //前進消去 for (int j = i + 1; j <= n; ++j) { //aji = 0 double alpha = -a[j][i] / a[i][i]; for (int k = i; k <= n; ++k) { a[j][k] += alpha * a[i][k]; } b[j][0] += alpha * b[i][0]; } for (int j = 1; j <= n; ++j) { for (int k = 1; k <= n; ++k) { cout << a[j][k] << " "; } cout << endl; } for (int j = 1; j <= n; ++j) { cout << b[j][0] << endl; } cout << endl; } //後退代入 b[n][0] /= a[n][n]; cout << b[n][0] << endl; for (int i = n - 1; i >= 1; --i) { double sum = 0; for (int j = i + 1; j <= n; ++j) { sum += a[i][j] * b[j][0]; } b[i][0] = (b[i][0] - sum) / a[i][i]; cout << b[i][0] << endl; } return 0; }
ピボット選択付きガウス消去法
RECOMMEND