IseNgaRt
IseNgaRt

Reputation: 609

Euclidian Distance math error

import math
from math import sqrt

Hailey=[0,4,1,4,0,0,4,1]
Verica=[3,0,0,5,4,2.5,3,0]
temp=[]
distance=0
x=0

for i in range(0,len(Hailey)):
    if (Hailey[i]!=0 and Verica[i]!=0):
        temp[x]=math.sqrt(abs(Hailey[i]**2) - abs(Verica[i]**2))
        x=x+1
for i in range(0,len(temp)):
    distance=distance+temp[i]
print("distance is",distance)   

Im trying to make a program that finds the euclidian distance between 2 people. It doesnt seem mathematically corret and im getting this:

    distance=distance + math.sqrt(abs(Hailey[i]**2) - abs(Verica[i]**2))
ValueError: math domain error

Upvotes: 2

Views: 258

Answers (1)

NPE
NPE

Reputation: 500257

The formula you are using isn't quite right. Here is the correct formula:

>>> math.sqrt(sum((h-v)**2 for h, v in zip(Hailey, Verica)))
7.158910531638177

Or, if you feel like using NumPy:

>>> Hailey = numpy.array([0,4,1,4,0,0,4,1])
>>> Verica = numpy.array([3,0,0,5,4,2.5,3,0])
>>> numpy.linalg.norm(Hailey - Verica)
7.1589105316381767

Upvotes: 6

Related Questions