高斯消去法
Ax=b
======================
E1 : -x1 + x2 + 2x3 = 2
E2 : 3x1 - x2 + x3 = 6
E3 : -x1 + 3x2 + 4x3 = 4
======================
/* ex6-1.c based on Gaussian Elimination method
* for solving the n x n linear algebra system
* a11 x1+a12 x2+...+a1n xn=b1
* a21 x1+a22 x2+...+a2n xn=b2
* . . . .
* . . . .
* an1 x1+an2 x2+...+ann xn=bn
* Input number of unknowns and equations n
* with coefficent a11,a12,...,ann and b1,b2,
* ...bn. Output solution x1,x2,x3,...,xn.
*/
#include <stdio.h>
#include <math.h>
#define MAX 20
void gaussh(int n,double a[MAX][MAX],double x[]);
void main()
{
int i,j,k,m,n;
double a[MAX][MAX],x[MAX];
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n+1;j++)
{
scanf("%lf",&a[i][j]);
printf("%6.3lf ",a[i][j]);
}
printf("\n");
}
gaussh(n,a,x); /* call the function gaussh() */
for(i=1;i<=n;i++)
printf("x%d=%6.3lf\n",i,x[i]);
return;
}
void gaussh(int n,double a[MAX][MAX],double x[])
{
int i,j,k,m;
double temp,bb,cc;
for(k=1;k<=n-1;k++)
{
/* check if a[k][k]=0 is true then interchange */
/* E(k) and E(k+1).............................*/
if(a[k][k]==0)
{
for(m=1;m<=n+1;m++)
{
temp=a[k][m];
a[k][m]=a[k+1][m];
a[k+1][m]=temp;
}
}
/* To reduce the matrix to triangular form */
for(i=k;i<=n-1;i++)
{
bb=a[i+1][k]/a[k][k];
for(j=k;j<=n+1;j++)
a[i+1][j]=a[i+1][j]-bb*a[k][j];
}
}
if(fabs(a[n][n])==0.0)
{
printf("NO UNIQUE SOLUTION!!!\n");
exit(1);
}
/* To start backward substitution */
x[n]=a[n][n+1]/a[n][n];
for(i=n-1;i>=1;i--)
{
cc=0.0;
for(j=i+1;j<=n;j++)
cc=cc+a[i][j]*x[j];
x[i]=(a[i][n+1]-cc)/a[i][i];
}
return;
}
=================================================
輸入資料
3
-1.0 1.0 2.0 2.0
3.0 -1.0 1.0 6.0
-1.0 3.0 4.0 4.0
=================================================
輸出結果
Compiled Successfully. memory: 1556 time: 0.02 exit code: 10
-1.000 1.000 2.000 2.000
3.000 -1.000 1.000 6.000
-1.000 3.000 4.000 4.000
x1= 1.000
x2=-1.000
x3= 2.000
沒有留言:
張貼留言