Correlation and the best-fit line

Given pairs (x, y), print Pearson's correlation r and the least-squares line y = a + b·x.

Input

The first line is n (2 to 1000). Each of the next n lines has x and y. The x values are not all equal, and neither are the y values.

Output

Three lines: r R, slope B and intercept A, each to 3 decimal places.

Examples

Example 1 · Input
6
1 52
2 55
3 61
4 64
5 70
6 73
Expected output
r 0.995
slope 4.371
intercept 47.200
Example 2 · Input
3
1 3
2 2
3 1
Expected output
r -1.000
slope -1.000
intercept 4.000

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

Hints

Hint 1

Work out the means of x and y first.

Hint 2

sxy = Σ(x − x̄)(y − ȳ), sxx = Σ(x − x̄)², syy = Σ(y − ȳ)².

Hint 3

r = sxy ÷ √(sxx × syy); slope b = sxy ÷ sxx; intercept a = ȳ − b·x̄.

Solution

Show one correct solution (try it yourself first)
n = int(input())
pts = [tuple(map(float, input().split())) for _ in range(n)]
mx = sum(x for x, _ in pts) / n
my = sum(y for _, y in pts) / n
sxy = sum((x - mx) * (y - my) for x, y in pts)
sxx = sum((x - mx) ** 2 for x, _ in pts)
syy = sum((y - my) ** 2 for _, y in pts)
b = sxy / sxx
print(f"r {sxy / (sxx * syy) ** 0.5:.3f}")
print(f"slope {b:.3f}")
print(f"intercept {my - b * mx:.3f}")

Lesson: Correlation and regression →