Free cookie consent management tool by TermsFeed Computing the Minkowski distance using Python | Pythontic.com

Computing the Minkowski distance using Python

Overview:

  • Minkowski distance between two n-dimensional points (x1, y1... Dn) and (x2, y2... Dn) is given by ((x1-y1)p + (x2-y1)p...+(xn - yn)p)1/p

  • The Minkowski distance is a metric that gives specialised distance for each value of the parameter p.

Example:

# Example Python program that finds the Minkowski distance between

two points on a 2-dimensional real plane for the parameter value 1, 2

# and ∞
import scipy.spatial.distance as dist
import numpy as np

# Points on a 2-dimensional plane
x = (2, 2)
y = (4, 5)

# Manhattan distance
d = dist.minkowski(x, y, p = 1)
print("Minkowski distance when p = 1")
print(d)

# Euclidean distance
d = dist.minkowski(x, y, p = 2)
print("Minkowski distance when p = 2")
print(d)

# Chebyshev distance
d = dist.minkowski(x, y, p = np.inf)
print("Minkowski distance when p = 3")
print(d)

Output:

Minkowski distance when p = 1
5.0
Minkowski distance when p = 2
3.605551275463989
Minkowski distance when p = 3
3.0

 


Copyright 2025 © pythontic.com