Minkowski distance in Python

PythonProgrammingServer Side Programming

The Minkowski distance is a metric and in a normed vector space, the result is Minkowski inequality. Minkowski distance is used for distance similarity of vector.

scipy.spatial.distance.minkowski

>>> from scipy.spatial import distance
>>> distance.minkowski([1, 0, 0], [0, 1, 0], 1)
2.0
>>> distance.minkowski([1, 0, 0], [0, 1, 0], 2)
1.4142135623730951
>>> distance.minkowski([1, 0, 0], [0, 1, 0], 3)
1.2599210498948732
>>> distance.minkowski([1, 1, 0], [0, 1, 0], 1)
1.0
>>> distance.minkowski([1, 1, 0], [0, 1, 0], 2)
1.0
>>> distance.minkowski([1, 1, 0], [0, 1, 0], 3)
1.0

Example code

from math import *
from decimal import Decimal
def my_p_root(value, root):
   my_root_value = 1 / float(root)
   return round (Decimal(value) **
   Decimal(my_root_value), 3)
def my_minkowski_distance(x, y, p_value):
   return (my_p_root(sum(pow(abs(a-b), p_value)
      for a, b in zip(x, y)), p_value))
# Driver Code
vector1 = [0, 2, 3, 4]
vector2 = [2, 4, 3, 7]
my_position = 5
print("The Distance is::",my_minkowski_distance(vector1, vector2, my_position))

Output

The Distance is:: 3.144
raja
Published on 22-Nov-2018 05:57:10
Advertisements