Finding the matrix eigenvectors using power iteration
Here’s an example of a Java program that uses power iteration to find the eigenvectors of a matrix:
import java.util.Arrays; public class PowerIteration { public static void main(String[] args) { double[][] matrix = {{2, 1}, {1, 3}}; // Example matrix double[] eigenvector = findEigenvector(matrix); System.out.println("Eigenvector: " + Arrays.toString(eigenvector)); } public static double[] findEigenvector(double[][] matrix) { int n = matrix.length; // Initialize a random vector double[] vector = new double[n]; for (int i = 0; i < n; i++) { vector[i] = Math.random(); } // Perform power iteration double epsilon = 1e-8; // Tolerance for convergence double error = Double.MAX_VALUE; int maxIterations = 1000; int iterations = 0; while (error > epsilon && iterations < maxIterations) { double[] newVector = multiplyMatrixVector(matrix, vector); double eigenvalue = calculateEigenvalue(vector, newVector); // Normalize the vector double norm = calculateNorm(newVector); for (int i = 0; i < n; i++) { vector[i] = newVector[i] / norm; } // Calculate the error error = Math.abs(eigenvalue - calculateEigenvalue(vector, newVector)); iterations++; } return vector; } public static double[] multiplyMatrixVector(double[][] matrix, double[] vector) { int n = matrix.length; double[] result = new double[n]; for (int i = 0; i < n; i++) { double sum = 0; for (int j = 0; j < n; j++) { sum += matrix[i][j] * vector[j]; } result[i] = sum; } return result; } public static double calculateEigenvalue(double[] oldVector, double[] newVector) { int n = oldVector.length; double eigenvalue = 0; for (int i = 0; i < n; i++) { eigenvalue += newVector[i] / oldVector[i]; } return eigenvalue / n; } public static double calculateNorm(double[] vector) { int n = vector.length; double sum = 0; for (int i = 0; i < n; i++) { sum += vector[i] * vector[i]; } return Math.sqrt(sum); } }
In this program, the `findEigenvector` method implements the power iteration algorithm to find the eigenvector corresponding to the largest eigenvalue of the given matrix. The `multiplyMatrixVector` method multiplies a matrix by a vector, the `calculateEigenvalue` method calculates an estimate of the eigenvalue using the old and new vectors, and the `calculateNorm` method calculates the Euclidean norm of a vector.
In the `main` method, we define an example matrix and call the `findEigenvector` method to obtain the eigenvector. Finally, the program prints the resulting eigenvector.
Note that this is a simplified implementation and may not work correctly for all matrices or handle edge cases. It is intended to serve as a starting point for understanding and implementing the power iteration algorithm in Java.