LUP分解求解线性方程组及求逆矩阵 java

具体的分析参考算法导论


public class LU
{
	/**矩阵相乘*/
	public static float[][] multiply(float[][]A,float[][]B){
		int n = A[0].length,i = 0,j = 0,k = 0;
		float[][] C = new float[n][n];
		for(i = 0;i < n;i++){
			for(j = 0;j < n;j++){
				for(k = 0;k < n;k++){
					C[i][j] += A[i][k]*B[k][j];
				}
			}
		}
		return C;
	}

	/**矩阵LU分解*/
	public static void LU_Decomposition(float[][] A,float[][] L,float[][] U){
		int n = A[0].length;
		float u = 0f,l = 0f;
		int i=0,j=0,k=0;
		//initial L and U
		for(i = 0;i < n-1;i++){
			u = A[i][i];
			//第j行
			for(j = i+1;j < n;j++){
				l = A[j][i]/u;
				A[j][i] = l;
				//update A'
				for(k = i+1;k < n;k++){
					A[j][k] = A[j][k] - l*A[i][k];
				}
			}
		}//for
		//make L and U
		for(i=0;i < n;i++){
			for(j = 0;j <= i;j++){
				if(i!=j)
					L[i][j] = A[i][j];
				else L[i][j] = 1;
			}
			for(k = i;k < n;k++){
				U[i][k] = A[i][k];
			}
		}
	}
	/**矩阵LUP分解
	*	相比LU分解,LUP分解可以防止出现除以0的情况和除数非常小导致计算不准确的情况
	*/
	public static void LUP_Decomposition(float[][] A,float[][] L,float[][] U,int[] P){
		int n = A[0].length;
		int i = 0,j = 0,k = 0,row = 0;
		for(i = 0;i < n;i++) P[i] = i;
		for(i = 0;i < n-1;i++){
			float p = 0f;
			for(j = i;j < n;j++){
				if(Math.abs(A[j][i]) > p){
					p = Math.abs(A[j][i]);
					row = j;
				}
			}
			if(p == 0) {System.err.println("singular matrix");return;}
			//exchange P[i] with P[row]
			int tmp = P[i];
			P[i] = P[row];
			P[row] = tmp;
			
			float tmp2 = 0f;
			for(j = 0;j < n;j++){
				//exchange A[i][j] with A[row][j]
				tmp2 = A[i][j];
				A[i][j] = A[row][j];
				A[row][j] = tmp2;
			}
			//下面与LU分解一样了
			float u = A[i][i],l = 0f;
			for(j = i+1;j < n;j++){
				l = A[j][i]/u;
				A[j][i] = l;
				//update A'
				for(k = i+1;k < n;k++){
					A[j][k] = A[j][k] - A[i][k]*l;
				}
			}
		}//for
		//make L and U
		for(i=0;i < n;i++){
			for(j = 0;j <= i;j++){
				if(i!=j)
					L[i][j] = A[i][j];
				else L[i][j] = 1;
			}
			for(k = i;k < n;k++){
				U[i][k] = A[i][k];
			}
		}
	}

	/**求解线性方程组
	*	Ax = b ==> PAx = Pb ==>LUx = Pb ==> Ly = Pb ==> Ux = y
	*/
	public static float[] LUP_Solve(float[][] L,float[][] U,int[]P,float[] b){
		int n = L[0].length,i = 0,j = 0;
		float[] x = new float[n];
		float[] y = new float[n];

		//正向替换
		for(i = 0;i < n;i++){
			y[i] = b[P[i]];
			for(j = 0;j < i;j++){
				y[i] = y[i] - L[i][j]*y[j];
			}
		}
		//反向替换
		for(i = n-1;i >= 0; i--){
			x[i] = y[i];
			for(j = n-1;j > i;j--){
				x[i] = x[i] - U[i][j]*x[j];
			}
			x[i] /= U[i][i];
		}
		return x;
	}
	/**矩阵置换*/
	public static float[][] transposition(float[][] A){
		int i=0,j=0,n = A[0].length;
		float tmp = 0f;
		for(i=0;i < n;i++){
			for(j=0;j


你可能感兴趣的:(算法与数据结构)