Skip to content
DeepForgeby svx
All problems
HardML Fundamentalsml-090

Mahalanobis Distance in 2D

Problem

Compute the Mahalanobis distance in 2D: sqrt(d^T * inv_cov * d), where d = x - mean and inv_cov is the 2x2 inverse covariance matrix.

Return 0.0 if the quadratic form is non-positive.

Hint

Expand d^T * inv_cov * d as a quadratic form in d0 and d1.

Test cases

case 1
in: [[3,4],[0,0],[[1,0],[0,1]]]
expected: 5
case 2
in: [[1,1],[0,0],[[2,0],[0,2]]]
expected: 2
case 3
in: [[1,-1],[0,0],[[1,-0.5],[-0.5,1]]]
expected: 1.7320508075688772
case 4
in: [[2,3],[2,3],[[1,0],[0,1]]]
expected: 0
Starter codePython
import math
def mahalanobis_distance_2d(x, mean, inv_cov):
    # Your code here
    pass

4 test cases · run your code against them in the editor