Pearson Correlation Coefficient Calculation
Pearson's $r$ measures linear correlation between two continuous variables on a scale from $-1.0$ (perfect inverse correlation) to $+1.0$ (perfect positive correlation). A score of $0.0$ indicates zero linear dependency 📊.
import math
def pearson_r(x, y):
n = len(x)
mean_x = sum(x) / n
mean_y = sum(y) / n
cov = sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y))
std_x = math.sqrt(sum((a - mean_x) ** 2 for a in x))
std_y = math.sqrt(sum((b - mean_y) ** 2 for b in y))
return cov / (std_x * std_y) if (std_x * std_y) else 0.0
hours = [1, 2, 3, 4, 5]
scores = [50, 60, 70, 80, 95]
print(f"r: {pearson_r(hours, scores):.4f} 📈")
# 51. Pearson Correlation Coefficient Calculation Pearson's $r$ measures linear correlation between two continuous variables on a scale from $-1.0$ (perfect inverse correlation) to $+1.0$ (perfect positive correlation). A score of $0.0$ indicates zero linear dependency 📊. ```python import math def pearson_r(x, y): n = len(x) mean_x = sum(x) / n mean_y = sum(y) / n cov = sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y)) std_x = math.sqrt(sum((a - mean_x) ** 2 for a in x)) std_y = math.sqrt(sum((b - mean_y) ** 2 for b in y)) return cov / (std_x * std_y) if (std_x * std_y) else 0.0 hours = [1, 2, 3, 4, 5] scores = [50, 60, 70, 80, 95] print(f"r: {pearson_r(hours, scores):.4f} 📈") ``` Remember: correlation never implies causation! A high Pearson $r$ means two lines travel together, not that one pushes the other off a cliff 📉. --- ### Question What does a Pearson correlation coefficient of $r = -0.95$ signify between study hours and gaming hours? 🧠- [ ] a. Strong negative linear relationship: more study hours correspond consistently to fewer gaming hours 📉 - [ ] b. Weak positive relationship with completely unpredictable cluster scattering - [ ] c. Study hours mathematically cause gaming hours to crash to zero - [ ] d. An arithmetic overflow error because correlation coefficients must always be non-negative --- ### Challenge Implement `pearson_r(x, y)` to calculate correlation. Compute `r` for `x = [1, 2, 3]` and `y = [2, 4, 6]`. Print `round(r, 2)`. 🎯 <details> <summary>Solution</summary> ```python import math def pearson_r(x, y): n = len(x) mx = sum(x) / n my = sum(y) / n num = sum((a - mx) * (b - my) for a, b in zip(x, y)) denom = math.sqrt(sum((a - mx) ** 2 for a in x)) * math.sqrt(sum((b - my) ** 2 for b in y)) return num / denom if denom else 0.0 print(round(pearson_r([1, 2, 3], [2, 4, 6]), 2)) ``` </details>