import numpy as np


def table4_3():
    # %% power method
    # %% note the values calculated will differ sightly from text because of the
    # %% random start

    # define A
    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 and number of iterations specified
    evalue = 1 + a
    K = 35

    # start-off info
    k = 0
    vv = 100
    y = np.random.rand(n)

    z = A @ y
    v = np.dot(y, z) / np.dot(y, y)
    err = abs(v - evalue)
    print("\n k  \t   x_k \t\t\t  Ratio1  \t  Ratio2 ")
    print(f" {k:d} \t {v:15.12f}  ")
    # print(f"{k:d} & {v:15.12f}    ")

    dv = 1.0
    dvv = 1.0
    for k in range(1, K + 1):
        vv = v
        dvv = dv
        errv = err
        y = z / np.linalg.norm(z, 2)
        z = A @ y
        v = np.dot(y, z)
        dv = v - vv
        err = abs(v - evalue)
        if k == 1:
            print(f" {k:d} \t {v:15.12f}  \t {np.divide(err, errv):5.2e}  ")
            # print(f"\\, {k:d} \\, & \\,\\, {v:15.12f} \\,\\, & \\,\\, {err/errv:5.2e}  \\,\\, & \\,\\,  \\\\ \\hline ")
        else:
            print(
                f" {k:d} \t {v:15.12f}  \t {np.divide(err, errv):5.2e}   \t "
                f"{np.divide(dv, dvv):5.2e} "
            )
            # print(f"\\, {k:d} \\, & \\,\\, {v:15.12f} \\,\\, & \\,\\, {err/errv:5.2e}  \\,\\, & \\,\\, {dv/dvv:5.2e} \\\\ \\hline ")


if __name__ == "__main__":
    table4_3()
