2-D dist functions
Skip Montanaro
skip at pobox.com
Fri May 30 16:35:40 EDT 2003
Brandon> I came up with these two functions that give the same result:
Brandon> def get_dist1(x1,y1,x2,y2):
Brandon> return math.hypot((x2-x1), (y2-y1))
Brandon> def get_dist2(x1,y1,x2,y2):
Brandon> return math.sqrt((x2-x1)**2 + (y2-y1)**2)
Brandon> However, the thing is that's strange to me is that get_dist1 is
Brandon> slower than get_dist2.
Look at the man page for hypot. It appears to do some extra work to avoid
intermediate underflows and overflows. On my Mac I see this:
The hypot() and cabs() functions computes the sqrt(x*x+y*y) in such a
way that underflow will not happen, and overflow occurs only if the
final result deserves it.
Extra numerical care equates to slower runtime.
Skip
More information about the Python-list
mailing list