Pearson Correlation Coefficient
Problem statement
Given two equal-length arrays x and y of paired observations, calculate their Pearson correlation coefficient without a statistics library.
Let mx and my be their arithmetic means. Return sum((x[i] - mx) * (y[i] - my)) / sqrt(sum((x[i] - mx)^2) * sum((y[i] - my)^2)). Each sum includes every index.
Both arrays have positive variance, so the denominator is nonzero. Keep the sign of the result; do not return covariance or its absolute value. The judged result uses absolute or relative tolerance 1e-6.
The arrays are provided so each run is reproducible. In a Python study session, you can also generate paired random arrays and check your calculation with numpy.corrcoef(x, y)[0, 1]; the judged implementation needs no NumPy dependency.
Function
correlation(x: double[], y: double[]) → doubleExamples
Example 1
x = [1,2,3]y = [2,4,6]return = 1.0A positive linear relationship has correlation 1.
Example 2
x = [1,2,3]y = [6,4,2]return = -1.0A negative linear relationship has correlation -1.
Example 3
x = [-1,0,1]y = [1,0,1]return = 0.0Centered cross-products cancel, while both variances are positive.
Constraints
2 <= x.length == y.length <= 100000.- Each observation is a finite integer represented as a double, with absolute value at most
1000000. - Each array contains at least two different values.
- Use double-precision arithmetic. NaN, infinities and constant arrays are outside the input contract.