Skip to content

Instantly share code, notes, and snippets.

@kamiyaowl
Created June 17, 2015 11:16
Show Gist options
  • Save kamiyaowl/ecf3a6259b668d1a40d8 to your computer and use it in GitHub Desktop.
Save kamiyaowl/ecf3a6259b668d1a40d8 to your computer and use it in GitHub Desktop.
ガウスの消去法
#include <stdio.h>
// 未知数の数/方程式の数
#define N 2
int main(void){
// x + 2y = 5
//2x + 3y = 8
double matrix[N][N + 1] = {
{ 1, 2, 5 },
{ 2, 3, 8 },
};
double answers[N];
/* 三角行列の生成 */
for (int j = 0; j < N; ++j){
//j列の対角成分で列すべての要素を割る
const double up_scale = matrix[j][j];
for (int i = j; i < N + 1; ++i) {
matrix[j][i] /= up_scale;
}
//jより下の列のj行目要素を0にする
for (int k = j + 1; k < N; ++k){
const double down_scale = matrix[k][j];
for (int i = j; i < N + 1; ++i){
matrix[k][i] -= matrix[j][i] * down_scale;
}
}
}
/* 列の下から順に解を確定させる */
for (int j = N - 1; j >= 0; --j){
//右辺の定数値
answers[j] = matrix[j][N];
for (int k = j + 1; k < N ; ++k){
//xを含む項は右辺に移行させるのでマイナス
answers[j] -= matrix[j][k] * answers[k];
}
}
/* 結果を出力 */
for (int j = 0; j < N; ++j){
printf("x_%d = %f\n", j, answers[j]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment