Data Visualization: The correlation coefficient

Put a number on how closely two variables follow a straight line.

What to build

A program that computes Pearson's r and describes its strength.

Requirements

  • Print r = R (LABEL) with R to three decimals and LABEL: strong positive if r ≥ 0.7, moderate positive if r ≥ 0.3, weak or none if r > −0.3, moderate negative if r > −0.7, otherwise strong negative.

Input

Line 1: the x values. Line 2: the y values (as many as x).

Output

One line.

Constraints

2 to 1000 pairs; neither the x values nor the y values are all equal.

Example

Input:

1 2 3 4
1 3 2 4

Output:

r = 0.800 (strong positive)

Why it works

Dividing the joint variation by the two separate variations removes the units, so r compares relationships on one scale from −1 to 1.

Examples

Example 1 · Input
1 2 3 4
1 3 2 4
Expected output
r = 0.800 (strong positive)
Example 2 · Input
1 2 3
3 2 1
Expected output
r = -1.000 (strong negative)

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

Hints

Hint 1

r = sxy / sqrt(sxx × syy), using deviations from the means.

Hint 2

Check the labels from strong positive downwards.

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()]
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)
r = sxy / (sxx * syy) ** 0.5
if r >= 0.7:
    label = "strong positive"
elif r >= 0.3:
    label = "moderate positive"
elif r > -0.3:
    label = "weak or none"
elif r > -0.7:
    label = "moderate negative"
else:
    label = "strong negative"
print(f"r = {r:.3f} ({label})")

Lesson: Scatter plots and correlation →