import numpy as np


def table4_7():
    # rayleigh quotient iteration

    # number of iterations
    K = 4

    # matrix
    n = 200
    a = 3
    A = np.zeros((n, n))
    for i in range(n):
        A[i, i] = a
    A[0, n - 1] = 1
    A[n - 1, 0] = 1

    # exact value
    evalue = 1 + a

    # start-off values
    k = 0
    err = 1
    y = np.random.rand(n)
    y = y / np.dot(y, y)
    z = A @ y
    v = np.dot(y, z)

    print("\n k  \t   v_k \t\t\t  Error ")
    print(f"{k:d} \t {v:15.12f}    ")
    # print(f"{k:d} & {v:15.12f} & {err:5.2e}   ")

    for k in range(1, K + 1):
        vv = v
        B = A - v * np.eye(n)
        z = np.linalg.solve(B, y)
        y = z / np.linalg.norm(z, 2)
        v = np.dot(y, A @ y)
        err = abs(v - 3)
        vv = v
        print(f"{k:d} \t {v:15.12f} \t {err:5.2e}   ")
        # print(f"{k:d} & {v:15.12f} & {err:5.2e}  ")
        if err == 0:
            break


if __name__ == "__main__":
    table4_7()
