Member-only story

Minkowski Distance in Python

Python Coding
Sep 2, 2024

--

The Minkowski distance is a generalization of various distance metrics like Euclidean and Manhattan distances.

import numpy as np

def minkowski_distance(x, y, p):
return np.sum(np.abs(x - y) ** p) ** (1 / p)

# Example usage
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])

# Calculate Minkowski distance with p=3
distance = minkowski_distance(x, y, p=3)
print("Minkowski Distance:", distance)
Minkowski Distance: 4.3267487109222245

Explanation:

  • x and y: The points in an n-dimensional space, represented as NumPy arrays.
  • p: The parameter p in the Minkowski distance formula. For p=1, it becomes the Manhattan distance; for p=2, it becomes the Euclidean distance.
  • np.abs(x - y) ** p: Calculates the absolute differences raised to the power of p for each dimension.
  • np.sum(... ** (1 / p)): Sums these values and then takes the pth root.

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet