Finding the matrix eigenvalues using Givens rotation
Here’s an example Java code that uses Givens rotation to find the eigenvalues of a matrix:
import java.util.Arrays; public class MatrixEigenvalues { private static final double EPSILON = 1e-10; // Tolerance for convergence public static double[] findEigenvalues(double[][] matrix) { int n = matrix.length; double[] eigenvalues = new double[n]; double[][] eigenMatrix = matrix.clone(); // Iterate until convergence while (true) { double maxOffDiagonal = 0.0; int p = 0, q = 0; // Find the maximum off-diagonal element for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (Math.abs(eigenMatrix[i][j]) > maxOffDiagonal) { maxOffDiagonal = Math.abs(eigenMatrix[i][j]); p = i; q = j; } } } // If maximum off-diagonal is below the tolerance, convergence reached if (maxOffDiagonal < EPSILON) { break; } // Perform Givens rotation double a_pp = eigenMatrix[p][p]; double a_pq = eigenMatrix[p][q]; double a_qq = eigenMatrix[q][q]; double theta = 0.5 * Math.atan2(2 * a_pq, a_qq - a_pp); double c = Math.cos(theta); double s = Math.sin(theta); // Update eigenMatrix with the Givens rotation for (int i = 0; i < n; i++) { double old_p = eigenMatrix[i][p]; double old_q = eigenMatrix[i][q]; eigenMatrix[i][p] = c * old_p + s * old_q; eigenMatrix[i][q] = -s * old_p + c * old_q; } for (int j = 0; j < n; j++) { double old_p = eigenMatrix[p][j]; double old_q = eigenMatrix[q][j]; eigenMatrix[p][j] = c * old_p + s * old_q; eigenMatrix[q][j] = -s * old_p + c * old_q; } } // Extract eigenvalues from the diagonal of the converged matrix for (int i = 0; i < n; i++) { eigenvalues[i] = eigenMatrix[i][i]; } return eigenvalues; } public static void main(String[] args) { double[][] matrix = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}}; double[] eigenvalues = findEigenvalues(matrix); System.out.println("Eigenvalues: " + Arrays.toString(eigenvalues)); } }
In this code, the `findEigenvalues` method takes a matrix as input and uses the Givens rotation algorithm to iteratively compute the eigenvalues. The convergence is determined by the maximum off-diagonal element of the matrix falling below a specified tolerance (`EPSILON`).
In the `main` method, a sample 3×3 matrix is defined, and the `findEigenvalues` method is called to compute the eigenvalues. The resulting eigenvalues are then printed to the console.
Note that this is a simplified implementation for demonstration purposes, and it
assumes that the input matrix is square. In practice, you may need to handle additional cases and perform error-checking to ensure the matrix is valid.