Covariance and Correlation

~12 mincode completion

Implement correlation(x, y) from the definition, returning as a float. The cancels between numerator and denominator, but compute it honestly rather than relying on that.

Examples

A perfect straight line upward

Input
correlation([1, 2, 3], [2, 4, 6])
Output
1

A perfect straight line downward

Input
correlation([1, 2, 3], [6, 4, 2])
Output
-1

A symmetric parabola is perfectly determined and yet uncorrelated

Input
correlation([-2, -1, 0, 1, 2], [4, 1, 0, 1, 4])
Output
0

Hints

Hint 1

Take the square root at the end, not inside the sum.

Hint 2

Watch for this: forgets to centre one of the variables.

Requirements

  • x: array of shape (n,)

  • y: array of shape (n,)

  • Return float in [-1, 1]

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~12 min

8 employers weight this skill

4 quant funds, 2 health and bio companies, 2 big tech firms. Top match scores 93.

Python
import numpy as np


def correlation(x, y):
    """
    Pearson correlation coefficient.

    Args:
        x: array of shape (n,)
        y: array of shape (n,)

    Returns:
        float in [-1, 1]
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.