求助,高斯消元法解线性方程组结果不对
程序运行没有任何错误,但解出来的结果却不对,请各位指教!下面是代码,谢谢!
/* @author :young
* @date :2009
* @version :0.0
* this class is used to solve linear equation group,the parameter
* you need to input is the number of equation n,
* the coefficient matrix A, constant vector b
* the algorithm is Gauss elimination
*/
package computation;
import java.util.Scanner;
public class linearVersion3 {
private int n;
private double[][] A;
private double[] b;
private Scanner input;
public linearVersion3(){
super();
input=new Scanner(System.in);
System.out.println("Input n,e");
n=input.nextInt();
A=new double[n][n];
b=new double[n];
System.out.println("input matrix A");//initialize coefficient matrix A
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
A[i][j]=input.nextDouble();
System.out.println("input vector b");//initialize vector b
for(int i=0;i<n;i++)
b[i]=input.nextDouble();
for(int k=0;k<n-1;k++){ //elimination coefficient matrix A to make sure matrix A is upper triangle matrix
double max=A[k][k];//initialize max
int inc=0;
for(int i=k+1;i<n;i++) //find max
if(A[i][k]>max){
max=A[i][k];
inc++;
}//end for
if(inc>0){//change row k with row k+inc
for(int j=k;j<n;j++)
exchange(A[k][j],A[k+inc][j]);
exchange(b[k],b[k+inc]);
}//end if
for(int i=k+1;i<n;i++){
double m=0;
m=A[i][k]/A[k][k];
for(int j=k;j<n;j++)
A[i][j]-=m*A[k][j];
b[i]-=m*b[k];
}//end for
}
b[n-1]/=A[n-1][n-1];//backwards to calculate the roots and store then in vector b
for(int i=n-2;i>=0;i--){
double sum=0;
for(int j=i+1;j<n;j++)
sum+=A[i][j]*b[j];
b[i]=(b[i]-sum)/A[i][i];
}
for(int i=0;i<n;i++)//print the result
System.out.printf("x[%d]=%f ", i+1,b[i]);
}
public void exchange(double a,double b){
double temp=a;
a=b;
b=temp;
}
public static void main(String args[]){
new linearVersion3();
}
}
[ 本帖最后由 zjuyx 于 2009-12-19 21:00 编辑 ]