>>> test_power_iteration() # self running tests
()
| 82 | |
| 83 | |
| 84 | def test_power_iteration() -> None: |
| 85 | """ |
| 86 | >>> test_power_iteration() # self running tests |
| 87 | """ |
| 88 | real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]) |
| 89 | real_vector = np.array([41, 4, 20]) |
| 90 | complex_input_matrix = real_input_matrix.astype(np.complex128) |
| 91 | imag_matrix = np.triu(1j * complex_input_matrix, 1) |
| 92 | complex_input_matrix += imag_matrix |
| 93 | complex_input_matrix += -1 * imag_matrix.T |
| 94 | complex_vector = np.array([41, 4, 20]).astype(np.complex128) |
| 95 | |
| 96 | for problem_type in ["real", "complex"]: |
| 97 | if problem_type == "real": |
| 98 | input_matrix = real_input_matrix |
| 99 | vector = real_vector |
| 100 | elif problem_type == "complex": |
| 101 | input_matrix = complex_input_matrix |
| 102 | vector = complex_vector |
| 103 | |
| 104 | # Our implementation. |
| 105 | eigen_value, eigen_vector = power_iteration(input_matrix, vector) |
| 106 | |
| 107 | # Numpy implementation. |
| 108 | |
| 109 | # Get eigenvalues and eigenvectors using built-in numpy |
| 110 | # eigh (eigh used for symmetric or hermetian matrices). |
| 111 | eigen_values, eigen_vectors = np.linalg.eigh(input_matrix) |
| 112 | # Last eigenvalue is the maximum one. |
| 113 | eigen_value_max = eigen_values[-1] |
| 114 | # Last column in this matrix is eigenvector corresponding to largest eigenvalue. |
| 115 | eigen_vector_max = eigen_vectors[:, -1] |
| 116 | |
| 117 | # Check our implementation and numpy gives close answers. |
| 118 | assert np.abs(eigen_value - eigen_value_max) <= 1e-6 |
| 119 | # Take absolute values element wise of each eigenvector. |
| 120 | # as they are only unique to a minus sign. |
| 121 | assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6 |
| 122 | |
| 123 | |
| 124 | if __name__ == "__main__": |
no test coverage detected