Skip to content

Commit 96fe376

Browse files
dbringsedatguzelsemme
authored andcommitted
Added the Minkowski distance function (TheAlgorithms#10143)
* Added the Minkowski distance function * Made error handling more precise * Added note about floating point errors and corresponding doctest
1 parent 46bbba5 commit 96fe376

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Diff for: maths/minkowski_distance.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
def 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+
>>> 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+
42+
if __name__ == "__main__":
43+
import doctest
44+
45+
doctest.testmod()

0 commit comments

Comments
 (0)