C++ で連立一次方程式を解く(ガウス・ザイデル法)
考え方は、ヤコビ法とほぼ同じ.
ヤコビ法の場合、漸化式で書くと
だったが、2番目以降の式のの代わりに,
1番目の式で計算して得られたを使う.
同様に、3番目以降の式のの代わりに,
2番目の式で計算して得られたを使う.
まとめると、
#include <iostream> #include <iomanip> #include <math.h> using namespace std; void gauss(double a[4][4], double b[4], double c[4]); int main() { double a[4][4] = {{9,2,1,1},{2,8,-2,1},{-1,-2,7,-2},{1,-1,-2,6}}; double b[4] = {20,16,8,17}; double c[4] = {0,0,0,0}; gauss(a,b,c); for (int i = 0;i<=3;i++) cout << setw(12) << fixed << setprecision(10) << c[i] << "\t"; cout << endl; return 0; } void gauss(double a[4][4], double b[4], double c[4]) { for (int n = 0;n<=100;n++) { double s; double e = 0; for (int i = 0;i<=3;i++) { s = b[i]; for (int j=0; j<=(i-1);j++) s -= a[i][j] * c[j]; for (int j=i+1;j<=3; j++) s -= a[i][j] * c[j]; s /= a[i][i]; e += fabs(s - c[i]); c[i] = s; cout << setw(12) << fixed << setprecision(10) << c[i] << "\t"; } cout << endl; if (e <= 0.0000000001) return; } cout << "収束しない" << endl; }
2.2222222222 1.4444444444 1.8730158730 3.3280423280 1.3233392122 1.7214138742 2.7746073738 3.8245482349 1.1064462937 1.9389717407 2.9476408921 3.9546345385 1.0244201209 1.9864758755 2.9866629927 3.9892302900 1.0056838851 1.9965909906 2.9967609209 3.9974048246 1.0014058081 1.9991631751 2.9992202582 3.9993663139 1.0003430086 1.9997985232 2.9998103832 3.9998460468 1.0000829471 1.9999511032 2.9999538924 3.9999626568 1.0000201383 1.9999881064 2.9999888093 3.9999909311 1.0000048941 1.9999971124 2.9999972830 3.9999977974 1.0000011883 1.9999992990 2.9999993402 3.9999994652 1.0000002885 1.9999998298 2.9999998398 3.9999998701 1.0000000701 1.9999999587 2.9999999611 3.9999999685 1.0000000170 1.9999999900 2.9999999906 3.9999999923 1.0000000041 1.9999999976 2.9999999977 3.9999999981 1.0000000010 1.9999999994 2.9999999994 3.9999999995 1.0000000002 1.9999999999 2.9999999999 3.9999999999 1.0000000001 2.0000000000 3.0000000000 4.0000000000 1.0000000000 2.0000000000 3.0000000000 4.0000000000 1.0000000000 2.0000000000 3.0000000000 4.0000000000 1.0000000000 2.0000000000 3.0000000000 4.0000000000