2019-01-29 21:14:07 UNSELECTED

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

Copy Copied! Full
#include <stdio.h> #include<iostream> using namespace std; #include <stdlib.h> #include <math.h> #define N 4 /* N次正方行列 */ #define n 4 int main(void) { int i, j, k, ip; double alpha, tmp; double amax, eps=pow(2.0, -50.0); /* eps = 2^{-50}とする */ 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] = {0, 0, 10, 2, 6}; for( k = 1; k <= N-1; k++) { /* ピボットの選択 */ amax = fabs(a[k][k]); ip = k; for( i = k+1; i <= N; i++) { if ( fabs(a[i][k]) > amax ) { amax = fabs(a[i][k]); ip = i; } } /* 正則性の判定 */ if ( amax < eps ) printf("入力した行列は正則ではない!!\n"); /* 行交換 */ if ( ip != k) { for( j = k; j <= N; j++) { tmp = a[k][j]; a[k][j]=a[ip][j]; a[ip][j]=tmp; } tmp = b[k] ; b[k]=b[ip]; b[ip]=tmp; } /* 前進消去 */ for( i = k+1; i <= N; i++) { alpha = - a[i][k]/a[k][k]; for( j = k; j <= N; j++) { a[i][j] = a[i][j] + alpha * a[k][j]; } b[i] = b[i] + alpha * b[k]; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { cout << a[i][j] << " "; } cout << endl; } cout << endl; } /* 後退代入 */ b[N] = b[N]/a[N][N]; for( k = N-1; k >= 1; k--) { tmp = b[k]; for( j = k+1; j <= N; j++) { tmp = tmp - a[k][j] * b[j]; } b[k] = tmp/a[k][k]; } for (int i = 1; i <= n; ++i) { std::cout << b[i] << std::endl; } return 0; }
ピボット選択付きガウス消去法
RECOMMEND