Pagini recente » Cod sursa (job #2203075) | Cod sursa (job #2905872) | Cod sursa (job #3144086) | Cod sursa (job #2148845) | Cod sursa (job #2604138)
#include <fstream>
#include <cmath>
#include <iomanip>
using namespace std;
ifstream fin("gauss.in");
ofstream fout("gauss.out");
const int NMax = 300;
const double EPS = 0.001;
int N, M;
double A[NMax + 5][NMax + 5], X[NMax + 5];
int main()
{
fin >> N >> M;
for(int i = 1; i <= N; i++)
for(int j = 1; j <= M + 1; j++)
fin >> A[i][j];
int i = 1, j = 1, k;
double ct;
while(i <= N && j <= M)
{
///swap with another row that has non-zero pivot
for(k = i; k <= N; k++)
if(fabs(A[k][j]) > EPS)
break;
if(k == N + 1)
{
j++;
continue;
}
swap(A[i], A[k]);
///divide by pivot for the ease of calculation
ct = A[i][j];
for(k = j; k <= M + 1; k++)
A[i][k] /= ct;
///make every element below pivot zero
for(int x = i + 1; x <= N; x++)
{
ct = A[x][j];
for(int y = j; y <= M + 1; y++)
A[x][y] -= ct * A[i][y];
}
i++, j++;
}
///compute the solution vector X
for(i = N; i > 0; i--)
for(j = 1; j <= M + 1; j++)
if(fabs(A[i][j]) > EPS)
{
/// 0 * x == non-zero (absurd)
if(j == M + 1)
{
fout << "Imposibil\n";
return 0;
}
X[j] = A[i][M + 1];
for(k = j + 1; k <= M; k++)
X[j] -= X[k] * A[i][k];
break;
}
for(j = 1; j <= M; j++)
fout << fixed << setprecision(4) << X[j] << " ";
fin.close();
fout.close();
return 0;
}