Data Visualization: Fit a trend line

Fit the least-squares line through a scatter plot, measure how well it explains the data, and find the point it explains worst.

What to build

A program that fits a line, reports R², the largest residual and predictions.

Requirements

  • Print y = A + Bx with two decimals (y = A - |B|x when B is negative), then R^2 = R with three decimals.
  • Then largest residual: (X, Y) with E, the point whose residual (observed minus predicted y, rounded to two decimals) has the largest size, the first such point in input order on a tie; X and Y written with :g, E with a sign and two decimals.
  • Then, for each new x, x = X -> y = P with P to two decimals and X written with :g.

Input

Line 1: the x values. Line 2: the y values. Line 3: the new x values.

Output

The line, R², the residual line, and one line per new x.

Constraints

2 to 1000 points; the x values are not all equal; 1 to 20 new x values.

Example

Input:

1 2 3 4
1 3 2 4
5

Output:

y = 0.50 + 0.80x
R^2 = 0.640
largest residual: (2, 3) with +0.90
x = 5 -> y = 4.50

Why it works

Least squares minimises the squared residuals, R² says what share of the variation the line explains, and the largest residual points to the observation the line fits worst.

Examples

Example 1 · Input
1 2 3 4
1 3 2 4
5
Expected output
y = 0.50 + 0.80x
R^2 = 0.640
largest residual: (2, 3) with +0.90
x = 5 -> y = 4.50
Example 2 · Input
0 1 2
1 1 4
10 -2
Expected output
y = 0.50 + 1.50x
R^2 = 0.750
largest residual: (1, 1) with -1.00
x = 10 -> y = 15.50
x = -2 -> y = -2.50

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

Hints

Hint 1

slope = sxy / sxx, intercept = mean(y) − slope × mean(x), and R² = sxy² / (sxx × syy).

Hint 2

Compare residuals after rounding them to two decimals, so tiny floating-point differences cannot decide a tie.

Solution

Show one correct solution (try it yourself first)
xs = [float(v) for v in input().split()]
ys = [float(v) for v in input().split()]
new = [float(v) for v in input().split()]
n = len(xs)
mx, my = sum(xs) / n, sum(ys) / n
sxy = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
sxx = sum((x - mx) ** 2 for x in xs)
syy = sum((y - my) ** 2 for y in ys)
slope = sxy / sxx
intercept = my - slope * mx
r2 = sxy * sxy / (sxx * syy) if syy else 1.0
sign = "+" if slope >= 0 else "-"
print(f"y = {intercept:.2f} {sign} {abs(slope):.2f}x")
print(f"R^2 = {r2:.3f}")
best = None
for x, y in zip(xs, ys):
    e = round(y - (intercept + slope * x), 2)
    if best is None or abs(e) > abs(best[2]):
        best = (x, y, e)
print(f"largest residual: ({best[0]:g}, {best[1]:g}) with {best[2] + 0:+.2f}")
for x in new:
    print(f"x = {x:g} -> y = {intercept + slope * x:.2f}")

Lesson: Scatter plots and correlation →