Pearson Correlation: Covariance Without the Units

Data ProcessingMedium+20 XP+15

Pearson Correlation: Covariance Without the Units

Covariance tells you the direction of a relationship but its size depends on the units. Pearson correlation divides that away, landing on a fixed scale from -1 to 1:

1 Σ (x - mean_x)(y - mean_y)
2r = ---------------------------------------------
3 sqrt(Σ (x - mean_x)² * Σ (y - mean_y)²)

Task: write pearson_correlation(x_values, y_values) returning r, rounded to 4 decimal places.

  • 1.0 is a perfect increasing straight line, -1.0 a perfect decreasing one, 0.0 no linear relationship.
  • If either variable has zero variance, return 0.0.

It only measures linear association. Points on a perfect parabola have an exact, deterministic relationship and can still score near zero — which is the standard argument for looking at a scatter plot before trusting any single correlation number.

Pearson Correlation Coefficient (r)

Centered Deviations | Core Dataset (r = 0.878)

x̄ = 3.0ȳ = 3.200224466

Standardized Deviation Tooltip

Hover over a point to inspect its centered deviations and cross-product!

The Pearson r numerator is the sum of (x − x̄)(y − ȳ). When both variables deviate in the same direction — both above their means, or both below — the product is positive, pushing r towards +1.

Examples

x_values = [1.0, 2.0, 3.0, 4.0]
y_values = [2.0, 4.0, 6.0, 8.0]
returns 1.0
x_values = [1.0, 2.0, 3.0]
y_values = [3.0, 2.0, 1.0]
returns -1.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run