Finding the matrix determinant using LU decomposition.
Here’s a Java program that calculates the determinant of a matrix using LU decomposition:
public class LUDeterminant { public static double determinant(double[][] matrix) { int n = matrix.length; double[][] luMatrix = new double[n][n]; for (int i = 0; i < n; i++) { System.arraycopy(matrix[i], 0, luMatrix[i], 0, n); } int[] pivotSign = new int[1]; double determinant = 1.0; if (luDecomposition(luMatrix, pivotSign)) { for (int i = 0; i < n; i++) { determinant *= luMatrix[i][i]; } determinant *= pivotSign[0]; } else { determinant = 0.0; } return determinant; } private static boolean luDecomposition(double[][] matrix, int[] pivotSign) { int n = matrix.length; int[] pivot = new int[n]; for (int i = 0; i < n; i++) { pivot[i] = i; } for (int k = 0; k < n; k++) { double maxPivot = 0.0; int maxIndex = -1; for (int i = k; i < n; i++) { double pivotValue = Math.abs(matrix[i][k]); if (pivotValue > maxPivot) { maxPivot = pivotValue; maxIndex = i; } } if (maxIndex == -1 || maxPivot == 0.0) { return false; } if (maxIndex != k) { double[] tempRow = matrix[k]; matrix[k] = matrix[maxIndex]; matrix[maxIndex] = tempRow; int tempPivot = pivot[k]; pivot[k] = pivot[maxIndex]; pivot[maxIndex] = tempPivot; pivotSign[0] *= -1; } double pivotValue = matrix[k][k]; for (int i = k + 1; i < n; i++) { matrix[i][k] /= pivotValue; for (int j = k + 1; j < n; j++) { matrix[i][j] -= matrix[i][k] * matrix[k][j]; } } } return true; } public static void main(String[] args) { double[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; double determinant = determinant(matrix); System.out.println("Determinant: " + determinant); } }
This program defines a class called `LUDeterminant` that contains two methods. The `determinant` method takes a 2D matrix as input and calculates its determinant using LU decomposition. The `luDecomposition` method performs the LU decomposition of the matrix and stores the result in a separate matrix. The `main` method demonstrates the usage of the `determinant` method by calculating the determinant of a sample matrix.
You can modify the `matrix` array in the `main` method to calculate the determinant of your desired matrix.
No comments yet! You be the first to comment.