TheAlgorithms-Python

Форк
0
/
minkowski_distance.py 
45 строк · 1.4 Кб
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()
46

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.