All problems
Mahalanobis Distance 2x2
Problem
The Mahalanobis distance between x and mean under the symmetric 2x2 covariance matrix [[a, b], [b, c]] is sqrt(d^T S^-1 d) with d = x - mean. Using det = a * c - b^2, d^T S^-1 d equals (c * d0^2 - 2 * b * d0 * d1 + a * d1^2) / det. Return 0.0 when the covariance is not positive definite or shapes are wrong.
Hint
Invert the 2x2 covariance with the determinant and compute the quadratic form.
Test cases
case 1
in: [[1,0],[0,0],[[1,0],[0,1]]]
expected: 1
case 2
in: [[1,1],[0,0],[[2,0],[0,2]]]
expected: 1
case 3
in: [[1,1],[0,0],[[2,1],[1,2]]]
expected: 0.816496580927726
case 4
in: [[2,3],[1,1],[[1,0.5],[0.5,1]]]
expected: 2
case 5
in: [[0,0],[1,1],[[1,0],[0,1]]]
expected: 1.4142135623730951
Starter codePython
import math
def mahalanobis_distance_2x2(x, mean, covariance):
# Your code here
pass5 test cases · run your code against them in the editor