Pagini recente » Cod sursa (job #2863169) | Cod sursa (job #1602940) | Cod sursa (job #548617) | Cod sursa (job #1105315) | Cod sursa (job #3343659)
#include <fstream>
#include <cmath>
#include <iomanip>
#define error 1e-3
using namespace std;
ifstream cin("gauss.in");
ofstream cout("gauss.out");
int n,m,i,j,where[305];
double a[305][305],sol[305],b[305][305];
bool gauss()
{
int i,j;
for(j=1; j<=m; j++)
{
sol[j]=0;
where[j]=0;
}
for(i=1,j=1; i<=n&&j<=m; j++)
{
int rand=i;
double val=fabs(a[i][j]);
for(int row=i; row<=n; row++)
{
if(fabs(val)<fabs(a[row][j]))
{
rand=row;
val=fabs(a[row][j]);
}
}
if(val<error) continue;
where[j]=i;
for(int col=j; col<=m+1; col++)
swap(a[i],a[rand]);
for(int row=1; row<=n; row++)
{
if(row!=i)
{
double c=a[row][j]/a[i][j];
for(int col=j; col<=m+1; col++)
a[row][col]-=c*a[i][col];
}
}
i++;
}
for(j=1;j<=m;j++)
{
if(where[j]!=0)
{
sol[j]=a[where[j]][m+1]/a[where[j]][j];
}
}
for(i=1;i<=n;i++)
{
double sum=0;
for(j=1;j<=m;j++)
sum+=sol[j]*b[i][j];
sum-=b[i][m+1];
if(fabs(sum)>error) return false;
}
return true;
}
int main()
{
cin>>n>>m;
for(i=1; i<=n; i++)
{
for(j=1; j<=m+1; j++)
{
cin>>a[i][j];
b[i][j]=a[i][j];
}
}
if(gauss())
{
for(i=1; i<=m; i++) cout<<fixed<<setprecision(10)<<sol[i]<<' ';
}
else cout<<"Imposibil";
return 0;
}