How to calculate Euclidean and Manhattan distance by using python


Euclidean Distance

Euclidean metric is the "ordinary" straight-line distance between two points.

if p = (p1, p2) and q = (q1, q2) then the distance is given by

Euclidean Distance

For three dimension, formula is Euclidean Distance

###################################
#	name:	eudistance_samples.py
#	desc:	Simple scatter plot 
#	date:	2018-08-28
#	Author:	conquistadorjd
###################################
from scipy import spatial
import numpy
from sklearn.metrics.pairwise import euclidean_distances

import math

print('*** Program started ***')


############ Calculating distance by using  python math function
############# 2 D array
x1 = [1,1]
x2 = [2,9]
eudistance =math.sqrt(math.pow(x1[0]-x2[0],2) + math.pow(x1[1]-x2[1],2) )
print("eudistance Using math ", eudistance)

############# 3 D array
# x1 = [1,1,4]
# x2 = [10,2,7]
# # Calculating distance by using math
# eudistance = math.sqrt(math.pow(x1[0]-x2[0],2) + math.pow(x1[1]-x2[1],2) + math.pow(x1[2]-x2[2],2) )
# print("eudistance Using math ", eudistance)

############ Calculating distance by using scipy
eudistance = spatial.distance.euclidean(x1, x2)
print("eudistance Using scipy", eudistance)


############ Calculating distance by using numpy
x1np=numpy.array(x1)
x2np=numpy.array(x2)
eudistance = numpy.sqrt(numpy.sum((x1np-x2np)**2))
print("eudistance Using numpy", eudistance)

eudistance = numpy.linalg.norm(x1np-x2np)
print("eudistance Using numpy", eudistance)


############ Calculating distance by using sklearn
eudistance =  euclidean_distances([x1np], [x2np]) # for some strange reasons, values needs be in 2-D array
print("eudistance Using sklearn", eudistance)

print('*** Program ended ***')

Manhattan distance

The distance between two points measured along axes at right angles. The Manhattan distance between two vectors (or points) a and b is defined as ∑i|ai−bi| over the dimensions of the vectors.

Manhattan distance

All paths from the bottom left to top right of this idealized city have the same distance.

Manhattan Distance

Reference:

https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.euclidean.html

post by Pravin


Comments