Friday, November 21, 2025
HomeLanguagesMinkowski distance in Python

Minkowski distance in Python

Minkowski distance is a metric in a normed vector space. Minkowski distance is used for distance similarity of vector. Given two or more vectors, find distance similarity of these vectors.

Mainly, Minkowski distance is applied in machine learning to find out distance similarity.

Examples : 

Input : vector1 = 0 2 3 4
        vector2 = 2, 4, 3, 7
        p = 3

Output : distance1 = 3.5033

Input : vector1 = 1, 4, 7, 12, 23
        vector2 = 2, 5, 6, 10, 20
        p = 2

Output : distance2 = 4.0

Note : Here distance1 and distance2 are almost same so it will be in same near region.  

Python3




# Python3 program to find Minkowski distance
 
# import math library
from math import *
from decimal import Decimal
 
# Function distance between two points
# and calculate distance value to given
# root value(p is root value)
def p_root(value, root):
     
    root_value = 1 / float(root)
    return round (Decimal(value) **
             Decimal(root_value), 3)
 
def minkowski_distance(x, y, p_value):
     
    # pass the p_root function to calculate
    # all the value of vector parallelly
    return (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]
p = 3
print(minkowski_distance(vector1, vector2, p))


Output : 

3.503

Time Complexity : O(N)

Auxiliary Space : O(N)

Reference : 
https://en.wikipedia.org/wiki/Minkowski_distance
 

RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6782 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11997 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7166 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS