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