Finding the matrix condition number using Gaussian elimination.
Here’s a Java program that calculates the condition number of a matrix using Gaussian elimination:
import java.util.Scanner; public class MatrixConditionNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows: "); int rows = scanner.nextInt(); System.out.print("Enter the number of columns: "); int cols = scanner.nextInt(); double[][] matrix = new double[rows][cols]; System.out.println("Enter the matrix elements row-wise:"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = scanner.nextDouble(); } } double conditionNumber = calculateConditionNumber(matrix); System.out.println("Condition Number: " + conditionNumber); scanner.close(); } public static double calculateConditionNumber(double[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; double[][] augmentedMatrix = new double[rows][cols + 1]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { augmentedMatrix[i][j] = matrix[i][j]; } augmentedMatrix[i][cols] = 1.0; } // Applying Gaussian elimination for (int i = 0; i < rows; i++) { if (augmentedMatrix[i][i] == 0) { System.out.println("Matrix is singular. Cannot calculate condition number."); return Double.NaN; } for (int j = i + 1; j < rows; j++) { double factor = augmentedMatrix[j][i] / augmentedMatrix[i][i]; for (int k = i; k < cols + 1; k++) { augmentedMatrix[j][k] -= factor * augmentedMatrix[i][k]; } } } // Calculating the norm of the matrix double norm = 0; for (int i = 0; i < rows; i++) { norm += Math.pow(augmentedMatrix[i][cols], 2); } norm = Math.sqrt(norm); // Calculating the inverse norm of the matrix double inverseNorm = 0; for (int i = 0; i < rows; i++) { double sum = 0; for (int j = 0; j < cols; j++) { sum += Math.pow(augmentedMatrix[i][j], 2); } inverseNorm += sum / Math.pow(augmentedMatrix[i][cols], 2); } inverseNorm = Math.sqrt(inverseNorm); return norm * inverseNorm; } }
In this program, we first take input from the user for the number of rows and columns of the matrix. Then, we input the matrix elements row-wise. The `calculateConditionNumber()` function applies Gaussian elimination to the matrix and computes the condition number using the norm and inverse norm of the matrix.
Note that this program assumes that the input matrix is non-singular (i.e., invertible). If the matrix is singular, it will display an error message and return `Double.NaN` (not a number) as the condition number.
You can compile and run this program to calculate the condition number of a matrix in Java.
No comments yet! You be the first to comment.