You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.6 KiB
C++

/*/This is a C++ Program to implement Gauss Jordan Elimination algorithm. In linear algebra, Gaussian elimination (also known as row reduction) is an algorithm for solving systems of linear equations. It is usually understood as a sequence of operations performed on the associated matrix of coefficients. This method can also be used to find the rank of a matrix, to calculate the determinant of a matrix, and to calculate the inverse of an invertible square matrix.*/
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i, j, k, n;
float a[10][10] = { 0 }, d;
cout << "No of equations ? ";
cin >> n;
cout << "Read all coefficients of matrix with b matrix too " << endl;
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
cin >> a[i][j];
for (i = 1; i <= n; i++)
for (j = 1; j <= 2 * n; j++)
if (j == (i + n))
a[i][j] = 1;
/************** partial pivoting **************/
for (i = n; i > 1; i--)
{
if (a[i - 1][1] < a[i][1])
for (j = 1; j <= n * 2; j++)
{
d = a[i][j];
a[i][j] = a[i - 1][j];
a[i - 1][j] = d;
}
}
cout << "pivoted output: " << endl;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n * 2; j++)
cout << a[i][j] << " ";
cout << endl;
}
/********** reducing to diagonal matrix ***********/
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n * 2; j++)
if (j != i)
{
d = a[j][i] / a[i][i];
for (k = 1; k <= n * 2; k++)
a[j][k] -= a[i][k] * d;
}
}
/************** reducing to unit matrix *************/
for (i = 1; i <= n; i++)
{
d = a[i][i];
for (j = 1; j <= n * 2; j++)
a[i][j] = a[i][j] / d;
}
cout << "your solutions: " << endl;
for (i = 1; i <= n; i++)
{
for (j = n + 1; j <= n * 2; j++)
cout << a[i][j] << " ";
cout << endl;
}
getch();
return 0;
}
/*No of equations ? 3
Read all coefficients of matrix with b matrix too
2 3 4
5 6 3
9 8 6
pivoted output:
9 8 6 0 0 1
2 3 4 1 0 0
5 6 3 0 1 0
your solutions:
-0.292683 -0.341463 0.365854
0.0731707 0.585366 -0.341463
0.341463 -0.268293 0.0731708*/