MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / minkowski_distance

Function minkowski_distance

maths/minkowski_distance.py:1–39  ·  view source on GitHub ↗

This function calculates the Minkowski distance for a given order between two n-dimensional points represented as lists. For the case of order = 1, the Minkowski distance degenerates to the Manhattan distance. For order = 2, the usual Euclidean distance is obtained. https://en.

(
    point_a: list[float],
    point_b: list[float],
    order: int,
)

Source from the content-addressed store, hash-verified

1def minkowski_distance(
2 point_a: list[float],
3 point_b: list[float],
4 order: int,
5) -> float:
6 """
7 This function calculates the Minkowski distance for a given order between
8 two n-dimensional points represented as lists. For the case of order = 1,
9 the Minkowski distance degenerates to the Manhattan distance. For
10 order = 2, the usual Euclidean distance is obtained.
11
12 https://en.wikipedia.org/wiki/Minkowski_distance
13
14 Note: due to floating point calculation errors the output of this
15 function may be inaccurate.
16
17 >>> minkowski_distance([1.0, 1.0], [2.0, 2.0], 1)
18 2.0
19 >>> minkowski_distance([1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], 2)
20 8.0
21 >>> import numpy as np
22 >>> bool(np.isclose(5.0, minkowski_distance([5.0], [0.0], 3)))
23 True
24 >>> minkowski_distance([1.0], [2.0], -1)
25 Traceback (most recent call last):
26 ...
27 ValueError: The order must be greater than or equal to 1.
28 >>> minkowski_distance([1.0], [1.0, 2.0], 1)
29 Traceback (most recent call last):
30 ...
31 ValueError: Both points must have the same dimension.
32 """
33 if order < 1:
34 raise ValueError("The order must be greater than or equal to 1.")
35
36 if len(point_a) != len(point_b):
37 raise ValueError("Both points must have the same dimension.")
38
39 return sum(abs(a - b) ** order for a, b in zip(point_a, point_b)) ** (1 / order)
40
41
42if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected