How could one write a C function that solves a set on n line

How could one write a C++ function that solves a set on n linear equations using the Jacobi iterative method? Including comments and specifying the functions parameters and return value?

Solution

// C++ Code for Jacobi Method

#include <cstdlib>
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
int n,i,j,itCount=0;
  
cout << \"Enter number of Equations: \";
cin >> n;
  
   // Create matrix A, B and C. Also a vector to store intermediate results.
   // Ax = B.
double a[n][n],b[n][1],x[n][1],T[n][1],e,k;
  
   // Enter the matrix of the form.
cout << \"[a].[x]=[b]\" << endl;
  
   // Enter the matrix A entries.
cout << \"Enter Matrix a:\" << endl;
for(i=0;i<n;i++)
   {
       for(j=0;j<n;j++)
       {
           cout << \"a[\" << i << \",\" << j << \"] = \";
           cin >> a[i][j];
       }
   }
  
   // Enter matrix B entries.
cout << \"Enter Matrix b:\" << endl;
for(j=0;j<n;j++)
{
cout << \"b[0,\" << j << \"] = \";
cin >> b[0][j];
}
  
   // Enter the accuracy required here.
cout << \"Enter the Accuracy: \";
cin >> e;
  
   // Vector to store intermediate results.
for (i=0;i<n;i++)
T[i][0]=0;
  
   // Iteration happens here.
while (itCount!=n)
{
itCount=0;
for (i=0;i<n;i++)
{
x[i][0]=(1/a[i][i])*(b[i][0]);
for (j=0;j<n;j++)
{
if (j!=i)
x[i][0]=x[i][0]-(1/a[i][i])*(a[i][j]*T[j][0]);
}
}
      
       // Check the result obtained here for specified accuracy.
for(i=0;i<n;i++)
{
k=fabs(x[i][0]-T[i][0]);
if (k<=e)
{
itCount=itCount+1;
}
}
      
       // Update the intermediate result here.
       for (i=0;i<n;i++)
           T[i][0]=x[i][0];
}
  
   // Displaying the results.
   cout << \"Roots of the equation are: \" << endl;
for (i=0;i<n;i++)
cout << \"x\" << i+1 << \"=\" << x[i][0] <<endl;
  
return 0;
}

Enter number of Equations: 3
[a].[x]=[b]   
Enter Matrix a:   
a[0,0] = 4
a[0,1] = -1   
a[0,2] = -1
a[1,0] = -2   
a[1,1] = 6
a[1,2] = 1
a[2,0] = -1   
a[2,1] = 1
a[2,2] = 7
Enter Matrix b:   
b[0,0] = 3
b[0,1] = 9
b[0,2] = -6
Enter the Accuracy: 0.00001   

Roots of the equation are:
x1=0.999997   
x2=2
x3=-0.999998

How could one write a C++ function that solves a set on n linear equations using the Jacobi iterative method? Including comments and specifying the functions pa
How could one write a C++ function that solves a set on n linear equations using the Jacobi iterative method? Including comments and specifying the functions pa

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site