Skip to content

Commit 53042f0

Browse files
Create RayleighQuotient.py (TheAlgorithms#1749)
* Create RayleighQuotient.py https://en.wikipedia.org/wiki/Rayleigh_quotient * Update RayleighQuotient.py * Update and rename RayleighQuotient.py to rayleigh_quotient.py * Update rayleigh_quotient.py * Update rayleigh_quotient.py python/black * Update rayleigh_quotient.py
1 parent 4866b13 commit 53042f0

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
https://en.wikipedia.org/wiki/Rayleigh_quotient
3+
"""
4+
import numpy as np
5+
6+
7+
def is_hermitian(matrix:np.matrix) -> bool:
8+
"""
9+
Checks if a matrix is Hermitian.
10+
11+
>>> import numpy as np
12+
>>> A = np.matrix([
13+
... [2, 2+1j, 4],
14+
... [2-1j, 3, 1j],
15+
... [4, -1j, 1]])
16+
>>> is_hermitian(A)
17+
True
18+
>>> A = np.matrix([
19+
... [2, 2+1j, 4+1j],
20+
... [2-1j, 3, 1j],
21+
... [4, -1j, 1]])
22+
>>> is_hermitian(A)
23+
False
24+
"""
25+
return np.array_equal(matrix, matrix.H)
26+
27+
28+
def rayleigh_quotient(A:np.matrix, v:np.matrix) -> float:
29+
"""
30+
Returns the Rayleigh quotient of a Hermitian matrix A and
31+
vector v.
32+
>>> import numpy as np
33+
>>> A = np.matrix([
34+
... [1, 2, 4],
35+
... [2, 3, -1],
36+
... [4, -1, 1]
37+
... ])
38+
>>> v = np.matrix([
39+
... [1],
40+
... [2],
41+
... [3]
42+
... ])
43+
>>> rayleigh_quotient(A, v)
44+
matrix([[3.]])
45+
"""
46+
v_star = v.H
47+
return (v_star * A * v) / (v_star * v)
48+
49+
50+
def tests() -> None:
51+
A = np.matrix([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]])
52+
v = np.matrix([[1], [2], [3]])
53+
assert is_hermitian(A), f"{A} is not hermitian."
54+
print(rayleigh_quotient(A, v))
55+
56+
A = np.matrix([[1, 2, 4], [2, 3, -1], [4, -1, 1]])
57+
assert is_hermitian(A), f"{A} is not hermitian."
58+
assert rayleigh_quotient(A, v) == float(3)
59+
60+
61+
if __name__ == "__main__":
62+
import doctest
63+
64+
doctest.testmod()
65+
tests()

0 commit comments

Comments
 (0)