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](https://wikimedia.org/api/rest_v1/media/math/render/svg/4febdae84cbc320c19dd13eac5060a984fd438d8)
For three dimension, formula is
![Euclidean Distance](https://wikimedia.org/api/rest_v1/media/math/render/svg/b48fad52918eb76d14c4f17973ae210f7c1a6312)
```python
###################################
# 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](https://wikimedia.org/api/rest_v1/media/math/render/svg/02436c34fc9562eb170e2e2cfddbb3303075b28e)
All paths from the bottom left to top right of this idealized city have the same distance.
![Manhattan Distance](https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/Manhattan_distance.svg/200px-Manhattan_distance.svg.png)
Reference:
https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.euclidean.html
This post is written by Pravin
Tags : Python
Share it :