MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / power_iteration

Function power_iteration

linear_algebra/src/power_iteration.py:4–81  ·  view source on GitHub ↗

Power Iteration. Find the largest eigenvalue and corresponding eigenvector of matrix input_matrix given a random vector in the same space. Will work so long as vector has component of largest eigenvector. input_matrix must be either real or Hermitian. Input input_matrix

(
    input_matrix: np.ndarray,
    vector: np.ndarray,
    error_tol: float = 1e-12,
    max_iterations: int = 100,
)

Source from the content-addressed store, hash-verified

2
3
4def power_iteration(
5 input_matrix: np.ndarray,
6 vector: np.ndarray,
7 error_tol: float = 1e-12,
8 max_iterations: int = 100,
9) -> tuple[float, np.ndarray]:
10 """
11 Power Iteration.
12 Find the largest eigenvalue and corresponding eigenvector
13 of matrix input_matrix given a random vector in the same space.
14 Will work so long as vector has component of largest eigenvector.
15 input_matrix must be either real or Hermitian.
16
17 Input
18 input_matrix: input matrix whose largest eigenvalue we will find.
19 Numpy array. np.shape(input_matrix) == (N,N).
20 vector: random initial vector in same space as matrix.
21 Numpy array. np.shape(vector) == (N,) or (N,1)
22
23 Output
24 largest_eigenvalue: largest eigenvalue of the matrix input_matrix.
25 Float. Scalar.
26 largest_eigenvector: eigenvector corresponding to largest_eigenvalue.
27 Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).
28
29 >>> import numpy as np
30 >>> input_matrix = np.array([
31 ... [41, 4, 20],
32 ... [ 4, 26, 30],
33 ... [20, 30, 50]
34 ... ])
35 >>> vector = np.array([41,4,20])
36 >>> power_iteration(input_matrix,vector)
37 (79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))
38 """
39
40 # Ensure matrix is square.
41 assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]
42 # Ensure proper dimensionality.
43 assert np.shape(input_matrix)[0] == np.shape(vector)[0]
44 # Ensure inputs are either both complex or both real
45 assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector)
46 is_complex = np.iscomplexobj(input_matrix)
47 if is_complex:
48 # Ensure complex input_matrix is Hermitian
49 assert np.array_equal(input_matrix, input_matrix.conj().T)
50
51 # Set convergence to False. Will define convergence when we exceed max_iterations
52 # or when we have small changes from one iteration to next.
53
54 convergence = False
55 lambda_previous = 0
56 iterations = 0
57 error = 1e12
58
59 while not convergence:
60 # Multiple matrix by the vector.
61 w = np.dot(input_matrix, vector)

Callers 1

test_power_iterationFunction · 0.85

Calls

no outgoing calls

Tested by 1

test_power_iterationFunction · 0.68