#350Pearson correlation coefficientEasyStatistics
Pearson correlation coefficient
Background
The Pearson correlation coefficient measures the strength and direction of the linear relationship between two variables, normalised to : is a perfect increasing line, a perfect decreasing line, and means no linear relationship. It is the covariance divided by the product of the two standard deviations.
Problem statement
Implement pearson_correlation(x, y) returning the Pearson correlation between two equal-length vectors:
Input
x—np.ndarrayof shape(n,).y—np.ndarrayof shape(n,).
Output
Returns a float in .
Examples
Example 1
Input: x = [1, 2, 3, 4], y = [2, 4, 6, 8]
Output: 1.0
Explanation: is a perfect increasing linear relationship, so .
Constraints
- Centre both vectors by their means before forming the products.
- Divide by the product of the centred-vector norms; the scale factors cancel, so sample-vs-population normalisation does not matter.
- Return a
float; the result lies in .
Notes
- Pearson captures only linear dependence — variables can be strongly related (e.g. ) yet have .
- is the cosine of the angle between the mean-centred vectors, which is why it is invariant to shifting and positive scaling of either variable.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •reference perfect positive line y=2x+1
- •example five-point dataset
- •sample perfect negative line