2020-02-14 11:56:56 +00:00
|
|
|
"""
|
|
|
|
https://en.wikipedia.org/wiki/Rayleigh_quotient
|
|
|
|
"""
|
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
|
2020-05-01 15:42:41 +00:00
|
|
|
def is_hermitian(matrix: np.array) -> bool:
|
2020-02-14 11:56:56 +00:00
|
|
|
"""
|
|
|
|
Checks if a matrix is Hermitian.
|
|
|
|
>>> import numpy as np
|
2020-05-01 15:42:41 +00:00
|
|
|
>>> A = np.array([
|
2020-02-14 11:56:56 +00:00
|
|
|
... [2, 2+1j, 4],
|
|
|
|
... [2-1j, 3, 1j],
|
|
|
|
... [4, -1j, 1]])
|
|
|
|
>>> is_hermitian(A)
|
|
|
|
True
|
2020-05-01 15:42:41 +00:00
|
|
|
>>> A = np.array([
|
2020-02-14 11:56:56 +00:00
|
|
|
... [2, 2+1j, 4+1j],
|
|
|
|
... [2-1j, 3, 1j],
|
|
|
|
... [4, -1j, 1]])
|
|
|
|
>>> is_hermitian(A)
|
|
|
|
False
|
|
|
|
"""
|
2020-05-01 15:42:41 +00:00
|
|
|
return np.array_equal(matrix, matrix.conjugate().T)
|
2020-02-14 11:56:56 +00:00
|
|
|
|
|
|
|
|
2020-05-01 15:42:41 +00:00
|
|
|
def rayleigh_quotient(A: np.array, v: np.array) -> float:
|
2020-02-14 11:56:56 +00:00
|
|
|
"""
|
|
|
|
Returns the Rayleigh quotient of a Hermitian matrix A and
|
|
|
|
vector v.
|
|
|
|
>>> import numpy as np
|
2020-05-01 15:42:41 +00:00
|
|
|
>>> A = np.array([
|
2020-02-14 11:56:56 +00:00
|
|
|
... [1, 2, 4],
|
|
|
|
... [2, 3, -1],
|
|
|
|
... [4, -1, 1]
|
|
|
|
... ])
|
2020-05-01 15:42:41 +00:00
|
|
|
>>> v = np.array([
|
2020-02-14 11:56:56 +00:00
|
|
|
... [1],
|
|
|
|
... [2],
|
|
|
|
... [3]
|
|
|
|
... ])
|
|
|
|
>>> rayleigh_quotient(A, v)
|
2020-05-01 15:42:41 +00:00
|
|
|
array([[3.]])
|
2020-02-14 11:56:56 +00:00
|
|
|
"""
|
2020-05-01 15:42:41 +00:00
|
|
|
v_star = v.conjugate().T
|
|
|
|
return (v_star.dot(A).dot(v)) / (v_star.dot(v))
|
2020-02-14 11:56:56 +00:00
|
|
|
|
|
|
|
|
|
|
|
def tests() -> None:
|
2020-05-01 15:42:41 +00:00
|
|
|
A = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]])
|
|
|
|
v = np.array([[1], [2], [3]])
|
2020-02-14 11:56:56 +00:00
|
|
|
assert is_hermitian(A), f"{A} is not hermitian."
|
|
|
|
print(rayleigh_quotient(A, v))
|
|
|
|
|
2020-05-01 15:42:41 +00:00
|
|
|
A = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]])
|
2020-02-14 11:56:56 +00:00
|
|
|
assert is_hermitian(A), f"{A} is not hermitian."
|
|
|
|
assert rayleigh_quotient(A, v) == float(3)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
|
|
|
tests()
|