+3 votes
in Programming Languages by (74.2k points)
edited by

I want to calculate the distance between two NumPy arrays using the following formula.

d = (sum[(xi - yi)2])1/2

Is there any Numpy function for the distance?

E.g.

x=np.array([2,4,6,8,10,12])

y=np.array([4,8,12,10,16,18])

d = 11.49

1 Answer

+1 vote
by (350k points)
selected by
 
Best answer

You can use the Numpy sum() and square() functions to calculate the distance between two Numpy arrays. You can also use euclidean() function of scipy.

Here is an example:

>>> import numpy as np
>>> x=np.array([2,4,6,8,10,12])
>>> y=np.array([4,8,12,10,16,18])
>>> d = np.sqrt(np.sum(np.square(x-y)))
>>> d
11.489125293076057

>>> from scipy.spatial.distance import euclidean
>>> euclidean(x,y)
11.489125293076057


If you just want to use the absolute value of the difference instead of square, you can use the following code:

>>> import numpy as np
>>> x=np.array([2,4,6,8,10,12])
>>> y=np.array([4,8,12,10,16,18])
>>> d = np.sum(np.abs(x-y))
>>> d
26


...