Jacobi Iteration Method Using C++ with Output
C++ program for solving system of linear equations using Jacobi Iteration Method.
C++ Program for Jacobi Iteration
#include<iostream>
#include<iomanip>
#include<math.h>
/* Arrange systems of linear
equations to be solved in
diagonally dominant form
and form equation for each
unknown and define here
*/
/* In this example we are solving
3x + 20y - z = -18
2x - 3y + 20z = 25
20x + y - 2z = 17
*/
/* Arranging given system of linear
equations in diagonally dominant
form:
20x + y - 2z = 17
3x + 20y -z = -18
2x - 3y + 20z = 25
*/
/* Equations:
x = (17-y+2z)/20
y = (-18-3x+z)/20
z = (25-2x+3y)/20
*/
/* Defining function */
#define f1(x,y,z) (17-y+2*z)/20
#define f2(x,y,z) (-18-3*x+z)/20
#define f3(x,y,z) (25-2*x+3*y)/20
using namespace std;
/* Main function */
int main()
{
float x0=0, y0=0, z0=0, x1, y1, z1, e1, e2, e3, e;
int step=1;
/* Setting precision and writing floating point values in fixed-point notation. */
cout<< setprecision(6)<< fixed;
/* Input */
/* Reading tolerable error */
cout<<"Enter tolerable error: ";
cin>>e;
cout<< endl<<"Count\tx\t\ty\t\tz"<< endl;
do
{
/* Calculation */
x1 = f1(x0,y0,z0);
y1 = f2(x0,y0,z0);
z1 = f3(x0,y0,z0);
cout<< step<<"\t"<< x1<<"\t"<< y1<<"\t"<< z1<< endl;
/* Error */
e1 = fabs(x0-x1);
e2 = fabs(y0-y1);
e3 = fabs(z0-z1);
step++;
/* Set value for next iteration */
x0 = x1;
y0 = y1;
z0 = z1;
}while(e1>e && e2>e && e3>e);
cout<< endl<<"Solution: x = "<< x1<<", y = "<< y1<<" and z = "<< z1;
return 0;
}
Output
Enter tolerable error: 0.0000001 Count x y z 1 0.850000 -0.900000 1.250000 2 1.020000 -0.965000 1.030000 3 1.001250 -1.001500 1.003250 4 1.000400 -1.000025 0.999650 5 0.999966 -1.000077 0.999956 6 1.000000 -0.999997 0.999992 7 0.999999 -1.000000 1.000000 8 1.000000 -1.000000 1.000000 9 1.000000 -1.000000 1.000000 Solution: x = 1.000000, y = -1.000000 and z = 1.000000
Recommended Readings