Project one vector onto another

The projection finds the point on a line that is closest to a given vector.

What to build

Project the vector b onto the vector a and print the projection and the residual.

Requirements

  • Compute k = (a·b) ÷ (a·a).
  • Print the projection k·a and the residual b − k·a.
  • Use 4 decimal places.

Input

Two lines, each with the same count (2 to 6) of whole numbers: a (not all zeros), then b.

Output

Two lines: projection followed by its entries, and residual followed by its entries, each to 4 decimal places.

Constraints

The entries are between -50 and 50.

Example

Input:

3 1
2 4

Output:

projection 3.0000 1.0000
residual -1.0000 3.0000

Why it works

The closest point to b on the line through a is the foot of the perpendicular. Requiring a·(b − k·a) = 0 gives k = (a·b) ÷ (a·a). The residual is then perpendicular to a.

Examples

Example 1 · Input
3 1
2 4
Expected output
projection 3.0000 1.0000
residual -1.0000 3.0000
Example 2 · Input
1 0
5 7
Expected output
projection 5.0000 0.0000
residual 0.0000 7.0000

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

Hints

Hint 1

Compute k = (a·b) ÷ (a·a) with dot products.

Hint 2

The projection is k times a. The residual is b minus the projection.

Hint 3

Print each entry with `round(v, 4) + 0.0` first, then `:.4f`.

Solution

Show one correct solution (try it yourself first)
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
k = sum(x * y for x, y in zip(a, b)) / sum(x * x for x in a)

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

print("projection", *[r(k * x) for x in a])
print("residual", *[r(y - k * x) for x, y in zip(a, b)])

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

Lesson: Projections and least squares →