Link to home
Start Free TrialLog in
Avatar of dadadude
dadadude

asked on

python: distance 2 vectors (faster method)

hello,
is there a faster way in python to computer the ditance between 2 vectors:
def Edistance(self,v1,v2):
		sum = 0
		for i in range(0,len(v1)):
			for j in range(0,len(v2)):
				sum = sum + sqrt((v1[i]-v2[j])**2)
		
		return sum

Open in new window

Avatar of Hamed Zaghaghi
Hamed Zaghaghi
Flag of Iran, Islamic Republic of image

Hi,
first of all i think that your distance computation is wrong, but you can use numpy arrays for fast array operations.
def Edistance(self,v1,v2):
        a = numpy.array(v1)
        b = numpy.array(v2)
        return sum((a-b)**2)

Open in new window

remember that do
import numpy

for more information, documentation and tutorials see http://www.scipy.org
Avatar of dadadude
dadadude

ASKER

yes i think the computation is wrong u are right.
Thank you for the explanation it's way faster.
did you get the answer?
ASKER CERTIFIED SOLUTION
Avatar of mish33
mish33
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok, then do this:

def Edistance(self,v1,v2):
        a = numpy.array(v1)
        b = numpy.array(v2)
        return sqrt(sum((a-b)**2))

Open in new window

thank you for the correction, Actually i also checked scipy they already have the function to compute the distance.

Y = pdist(self.data, 'euclidean')
distanceMatrix = squareform(Y)
good
Your question was "is there a faster way in python to computer the ditance between 2 vectors", you want faster method not a correction on your distance function,

At least you should split the points.