Power iteration

Power iteration finds the dominant eigenvector with nothing but multiplication, which makes it work on huge matrices.

What to build

Find the largest eigenvalue of a matrix with positive entries and its eigenvector by power iteration.

Requirements

  • Start with the vector of all ones and repeat 100 times: multiply by A, then divide by the entry of largest size.
  • Print the last stretch factor as the eigenvalue and the final vector.

Input

A whole number n (2 to 4), then n lines of n whole numbers, all positive or zero, with a clearly largest eigenvalue.

Output

Two lines: eigenvalue L and vector followed by the n entries, all to 4 decimal places.

Constraints

Entries are between 0 and 9.

Example

Input:

2
2 1
1 2

Output:

eigenvalue 3.0000
vector 1.0000 1.0000

Why it works

Writing the start vector as a mix of eigenvectors, each multiplication by A stretches each part by its own eigenvalue, so the part with the largest eigenvalue soon dominates. Dividing by the largest entry keeps the numbers from growing.

Examples

Example 1 · Input
2
2 1
1 2
Expected output
eigenvalue 3.0000
vector 1.0000 1.0000
Example 2 · Input
2
4 1
2 3
Expected output
eigenvalue 5.0000
vector 1.0000 1.0000

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Start with v = all ones. Repeat 100 times: w = A·v, size = largest absolute entry of w, v = w ÷ size.

Hint 2

After the loop, the last `size` is the eigenvalue and v is its eigenvector, with largest entry 1.

Hint 3

Print every number with `round(v, 4) + 0.0` then `:.4f`.

Solution

Show one correct solution (try it yourself first)
n = int(input())
A = [[int(x) for x in input().split()] for _ in range(n)]
v = [1.0] * n
size = 1.0
for _ in range(100):
    w = [sum(a * b for a, b in zip(row, v)) for row in A]
    size = max(abs(x) for x in w)
    v = [x / size for x in w]

def r(x):
    return f"{round(x, 4) + 0.0:.4f}"

print("eigenvalue", r(size))
print("vector", *[r(x) for x in v])

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Eigenvalues and eigenvectors →