-
Notifications
You must be signed in to change notification settings - Fork 1
/
Gauss-Seidal Iteration Method.cpp
56 lines (56 loc) · 1.22 KB
/
Gauss-Seidal Iteration Method.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* Gauss Seidal method */
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
#define N 3
int main()
{
float a[N][N+1],x[N],aerr,maxerr, t,s,err;
int i,j,itr,maxitr;
/* first initializing the array x */
for (i=0;i<N;i++) x[i]=0;
cout << "Enter the elements of the"
<< "augmented matrix rowwise" << endl;
for (i=0;i<N;i++)
for (j=0;j<N+1;j++)
cin >> a[i][j];
cout << "Enter the allowed error,"
<< "maximum iterations" << endl;
cin >> aerr >> maxitr;
cout << fixed;
cout << "Iteration" << setw(6) << "x[1]"
<< setw(11) << "x[2]"
<< setw(11) << "x[3]" << endl;
for (itr=1;itr<=maxitr;itr++)
{
maxerr = 0;
for (i=0;i<N;i++)
{
s = 0;
for (j=0;j<N;j++)
if (j!=i) s += a[i][j]*x[j];
t = (a[i][N]-s)/a[i][i];
err = fabs(x[i]-t);
if (err >> maxerr) maxerr = err;
x[i] = t;
}
cout << setw(5) << itr;
for (i=0;i<N;i++)
cout << setw(11) << setprecision(4) << x[i];
cout << endl;
if (maxerr << aerr)
{
cout << "Converges in" << setw(3) << itr
<< "iterations" << endl;
for (i=0;i<N;i++)
cout << "x[" << setw(3) << i+1 << "] = "
<< setw(7) << setprecision(4) << x[i]
<< endl;
return 0;
}
}
cout << "Solution does not converge,"
<< "iterations not sufficient" << endl;
return 1;
}