Skip to content

Commit f38f1a7

Browse files
committed
Implemented Lanczos Algorithm
1 parent 3e9ca92 commit f38f1a7

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import numpy as np
2+
def lanczos(A: np.ndarray) -> ([float], [float]):
3+
"""
4+
Implements the Lanczos algorithm for a symmetric matrix.
5+
6+
Parameters:
7+
-----------
8+
matrix : numpy.ndarray
9+
Symmetric matrix of size (n, n).
10+
11+
Returns:
12+
--------
13+
alpha : [float]
14+
List of diagonal elements of the resulting tridiagonal matrix.
15+
beta : [float]
16+
List of off-diagonal elements of the resulting tridiagonal matrix.
17+
"""
18+
n = A.shape[0]
19+
V = np.zeros((n, n))
20+
V[:, 0] = np.random.randn(n)
21+
V[:, 0] /= np.linalg.norm(V[:, 0])
22+
alpha = []
23+
beta = []
24+
for j in range(n):
25+
w = np.dot(A, V[:, j])
26+
alpha.append(np.dot(w, V[:, j]))
27+
if j == n - 1:
28+
break
29+
w -= alpha[j] * V[:, j]
30+
if j > 0:
31+
w -= beta[j - 1] * V[:, j - 1]
32+
beta.append(np.linalg.norm(w))
33+
V[:, j + 1] = w / beta[j]
34+
return alpha, beta

0 commit comments

Comments
 (0)