日期:2014-05-20 浏览次数:20859 次
/** * Inverse a matrix. * * @author Small_Light * @version InverseMatrix 0.1 */ import java.util.Scanner; public class InverseMatrix { public static void main(String args[]) { Scanner s = new Scanner(System.in); // System.out.println(" Please print the row of your mathix : "); System.out.println(" 请输入矩阵的行数 : "); int row = s.nextInt(); // System.out.println(" Please print your mathix : "); System.out.println(" 请输入你的矩阵: "); double[][] matrix_old = new double[row][row]; double[][] matrix_new = new double[row][row]; for (int i = 0; i < row; i++) { for (int j = 0; j < row; j++) { matrix_old[i][j] = s.nextInt(); matrix_new[i][j] = 0; if (i == j) { matrix_new[i][j] = 1; } } } // **************以上内容完成矩阵的读取并且创建单位矩阵************** double temp;// col =1;j=2~row for (int col = 0; col < row; col++) {// col表示为处理到第几列 for (int j = col + 1; j < row; j++) {// J标记为第几行 temp = -matrix_old[j][col] / matrix_old[col][col]; for (int i = 0; i < row; i++) {// 单独处理第J行的每一个元素 matrix_old[j][i] = matrix_old[j][i] + matrix_old[col][i] * temp; matrix_new[j][i] = matrix_new[j][i] + matrix_new[col][i] * temp; } } } // 处理成为了上阶梯矩阵 for (int i = 0; i < row; i++) {// i为行数,J为列数 for (int j = 0; j < row; j++) { if (i < j) { temp = matrix_old[i][j]; matrix_old[i][j] = matrix_old[j][i]; matrix_old[j][i] = temp; temp = matrix_new[i][j]; matrix_new[i][j] = matrix_new[j][i]; matrix_new[j][i] = temp; } } } for (int col = 0; col < row; col++) {// col表示为处理到第几列 for (int j = col + 1; j < row; j++) {// J标记为第几行 temp = -matrix_old[j][col] / matrix_old[col][col]; for (int i = 0; i < row; i++) {// 单独处理第J行的每一个元素 matrix_old[j][i] = matrix_old[j][i] + matrix_old[col][i] * temp; matrix_new[j][i] = matrix_new[j][i] + matrix_new[col][i] * temp; } } } for (int i = 0; i < row; i++) { temp = matrix_old[i][i]; for (int q = 0; q < row; q++) { matrix_old[i][q] = matrix_old[i][q] / temp; matrix_new[i][q] = matrix_new[i][q] / temp; } } // System.out.println("The inverse mathix is : "); System.out.println("该矩阵的逆矩阵是 : "); show(matrix_new); } public static void show(double[][] matrix) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.printf("%.4f\t",matrix[i][j] ); } System.out.println(); } } }