The least-squares line

Fit the least-squares line ŷ = w x + b to some points, and use it to predict.

Input

The first line has n (2 ≤ n ≤ 100). Each of the next n lines has a point x y; not all x are equal. Then a line with q (1 ≤ q ≤ 20), and q lines with one x each.

Output

First w W b B, with 4 decimal places each. Then one prediction per query, with 2 decimal places.

Examples

Example 1 · Input
5
600 70
800 95
1000 118
1200 140
1500 178
2
700
2000
Expected output
w 0.1188 b -0.9877
82.18
236.64
Example 2 · Input
5
1 2
2 4.5
3 5.5
4 8.5
5 9.5
1
6
Expected output
w 1.9000 b 0.3000
11.70

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

Hints

Hint 1

w = Σ(x − x̄)(y − ȳ) / Σ(x − x̄)², and b = ȳ − w x̄.

Hint 2

Work out the means first.

Hint 3

Predict with w * x + b.

Solution

Show one correct solution (try it yourself first)
n = int(input())
points = [tuple(map(float, input().split())) for _ in range(n)]
x_mean = sum(x for x, _ in points) / n
y_mean = sum(y for _, y in points) / n
w = sum((x - x_mean) * (y - y_mean) for x, y in points) / sum((x - x_mean) ** 2 for x, _ in points)
b = y_mean - w * x_mean
print(f"w {w:.4f} b {b:.4f}")
for _ in range(int(input())):
    print(f"{w * float(input()) + b:.2f}")

Lesson: Linear regression →