求线性方程组的解

package com.data.struct;

public class LinearEquotion {
	private double[][]A=new double[][]{
			{1,2,0},
			{3,4,4},
			{5,6,3}
	};
	private double[]B=new double[]{
			3,7,8
	};
	private double[][]L=new double[3][3];
	private double[][]U=new double[3][3];
	private int[]p=new int[3];
	
	private double[]X=new double[3];
	
	public void solve()throws Exception{
		lupDecomposition();
		double[]Y=new double[3];
		for(int i=0;i<3;i++){
			Y[i]=B[p[i]];
			double sub=0;
			for(int j=0;j<=i-1;j++){
				sub+=L[i][j]*Y[j];
			}
			Y[i]=Y[i]-sub;
		}
		for(int i=2;i>=0;i--){
			double sub=0;
			for(int j=i+1;j<3;j++){
				sub+=U[i][j]*X[j];
			}
			X[i]=(Y[i]-sub)/U[i][i];
		}
	}
	
	private void lupDecomposition()throws Exception{
		for(int i=0;i<3;i++){
			p[i]=i;
		}
		for(int k=0;k<3;k++){
			double s=0;
			int k2=k;
			for(int i=k;i<3;i++){
				if(Math.abs(A[i][k])>s){
					s=Math.abs(A[i][k]);
					k2=i;
				}
			}
			if(s==0){
				throw new Exception("error");
			}
			int tmp=p[k];
			p[k]=p[k2];
			p[k2]=tmp;
			for(int i=0;i<3;i++){
				double tmp2=A[k][i];
				A[k][i]=A[k2][i];
				A[k2][i]=tmp2;
			}
			for(int i=k+1;i<3;i++){
				A[i][k]=A[i][k]/A[k][k];
				for(int j=k+1;j<3;j++){
					A[i][j]=A[i][j]-A[i][k]*A[k][j];
				}
			}
			
		}
		for(int i=0;i<3;i++){
			for(int j=0;j<=i;j++){
				if(i==j){
					L[i][j]=1;
				}else{
					L[i][j]=A[i][j];
				}
			}
			for(int j=i;j<3;j++) {
				U[i][j]=A[i][j];
			}
		}
	}
	
	public void printL(){
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				System.out.print(L[i][j]+" ");
			}
			System.out.println();
		}
	}
	public void printU(){
		for(int i=0;i<3;i++){
			for(int j=0;j<3;j++){
				System.out.print(U[i][j]+" ");
			}
			System.out.println();
		}
	}
	
	public void print(){
		for(int i=0;i<X.length;i++){
			System.out.print(X[i]+" ");
		}
	}
	public static void main(String[] args) throws Exception{
		LinearEquotion l=new LinearEquotion();
		l.solve();
		//l.printL();
		//l.printU();
		l.print();

	}

}

你可能感兴趣的:(求线性方程组的解)