2019-01-30 12:14:06 C++

lu分解

Copy Copied! Full
#include<iostream> #include<cmath> using namespace std; int main() { const int n = 4; double a[n + 1][n + 1] = {{0, 0, 0, 0, 0}, {0, 0.291455, 0.965695, 0.766408, 0.087878}, {0, 0.944082, 0.146784, 0.975357, 0.773916}, {0, 590431, 0.284318, 0.923296, 0.297239}, {0, 0.562451, 9.385487, 0.915657, 0.825075}}; double b[n] = {0.377294, 0.739658, 0.466539, 0.665474}; int p[n]; for (int k = 1; k < n; ++k) { double amax = fabs(a[k][k]); int ip = k; for (int i = k + 1; i <= n; ++i) { if (abs(a[i][k]) > amax) { amax = abs(a[i][k]); ip = i; } //pibot selectionと同じやん } if (amax < 0.001) { cout << "not 正則" << endl; return 0; } p[k] = ip; //変わった if (ip != k) { for (int j = k; j <= n; ++j) { swap(a[k][j], a[ip][j]); } } for (int i = k + 1; i <= n; ++i) { double alpha = -a[i][k] / a[k][k]; a[i][k] = alpha; for (int j = k + 1; j <= n; ++j) { a[i][j] += alpha * a[k][j]; } } } for (int k = 1; k < n; ++k) { b[k] = b[p[k]]; for (int i = k + 1; k <= n; ++k) { b[i] += a[i][k] * b[k]; } } for (int k = n; k > 0; --k) { double sum = 0; for (int j = k + 1; j <= n; ++j) { sum += a[k][j] * b[j]; } b[k] = (b[k] - sum) / a[k][k]; cout << b[k] << endl; } return 0; }
lu分解
RECOMMEND