เมธอด Gauss-Seidel ใช้แก้ระบบสมการเชิงเส้นแบบวนซ้ำ (iterative method) นี่คือโปรแกรม C++ สำหรับใช้งานเมธอด Gauss-Seidel
อัลกอริทึม
Begin
รับมิติของเมทริกซ์ p และองค์ประกอบต่างๆ
รับค่าเริ่มต้นของ x และจำนวนการวนซ้ำ q
While q > 0
วนลูป for i = 0 ถึง p-1
เริ่มต้น n[i] = (b[i] / a[i][i])
วนลูป for j = 0 ถึง p-1
If (j == i) continue
n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j])
m[i] = n[i]
ลด q ลง
/* a[i][j] = เมทริกซ์นำเข้า, b[i] = ค่าด้านขวาของสมการ, m[i] = ค่าเริ่มต้นของ x */
Return 0
End
ตัวอย่างโค้ด
#include <iostream>
#include <conio.h>
using namespace std;
int main(void) {
float a[10][10], b[10], m[10], n[10];
int p = 0, q = 0, i = 0, j = 0;
cout << "Enter size of 2D array : ";
cin >> p;
for (i = 0; i < p; i++) {
for (j = 0; j < p; j++) {
cout << "a[" << i << ", " << j << " ]=";
cin >> a[i][j];
}
}
cout << "\nEnter values to the right side of equation\n";
for (i = 0; i < p; i++) {
cout << "b[" << i << ", " << j << " ]=";
cin >> b[i];
}
cout << "Enter initial values of x\n";
for (i = 0; i < p; i++) {
cout << "x:[" << i << "]=";
cin >> m[i];
}
cout << "\nEnter the no. of iteration : ";
cin >> q;
while (q > 0) {
for (i = 0; i < p; i++) {
n[i] = (b[i] / a[i][i]);
for (j = 0; j < p; j++) {
if (j == i) continue;
n[i] = n[i] - ((a[i][j] / a[i][i]) * m[j]);
m[i] = n[i];
}
cout << "x" << i + 1 << "=" << n[i] << " ";
}
cout << "\n";
q--;
}
return 0;
}
ผลลัพธ์
Enter size of 2D array : 2 a[0, 0 ]=1 a[0, 1 ]=2 a[1, 0 ]=3 a[1, 1 ]=4 Enter values to the right side of equation b[0, 2 ]=1 b[1, 2 ]=2 Enter initial values of x x:[0]=0 x:[1]=0 Enter the no. of iteration : 3 x1 = 1. x2 = -0.25 x1 = 1.5 x2 = -0.625 x1 = 2.25 x2 = -1.1875