2-D dist functions

Brandon Corfman bcorfman at amsaa.army.mil
Thu May 29 10:32:57 EDT 2003


Say you want to calculate the distance between two 2-D points in 
Euclidean space.

I came up with these two functions that give the same result:
def get_dist1(x1,y1,x2,y2):
    return math.hypot((x2-x1), (y2-y1))

def get_dist2(x1,y1,x2,y2):
    return math.sqrt((x2-x1)**2 + (y2-y1)**2)

However, the thing is that's strange to me is that get_dist1 is slower 
than get_dist2.

Running the following test function I get these results on my P4 2.5 GHz.

def tester():
     t = time.time()
     for i in range(0,1000000):
         x = get_dist1(50,20,30,10)
     print time.time() - t
     t = time.time()
     for i in range(0,1000000):
         x = get_dist2(50,20,30,10)
     print time.time() - t

 >>> dist.tester()
2.56200003624
2.17200005054

Shouldn't using math.hypot be faster? If not, why not?

Thanks,
Brandon





More information about the Python-list mailing list