On Tue, May 26, 2015, at 09:40, random...@fastmail.us wrote: > On Mon, May 25, 2015, at 15:21, ravas wrote: > > Is this valid? Does it apply to python? > > Any other thoughts? :D > > The math.hypot function uses the C library's function which should deal > with such concerns internally. There is a fallback version in case the C > library does not have this function, in Python/pymath.c - which, > incidentally, does use your algorithm.
Well, I should say, not _precisely_ your algorithm. The "0 special case" mentioned in the text you read was for both values being zero, not just one. The biggest flaw in your function, though, was the failure to take the absolute values of the differences. This defeats the point of swapping them (which I assume is to get the magnitudes in the order needed for best precision), and makes it possible for your function to return a negative value when the other is zero. Here's the equivalent python code for the hypot function in pymath.c, and for your distance function. from math import sqrt def hypot(x, y): x = abs(x) y = abs(y) if x < y: x, y = y, x if x == 0: # both are 0 due to the swap return 0.0 else: return x*sqrt(1.0 + (y/x)**2) def distance(A, B): return hypot(A.x-B.x, A.y-B.y) What I wonder is if there's a best way to do it for three dimensions. I mean, you could simply do hypot(hypot(dx, dy), dz), but should you choose the largest, smallest, or middle value to be the odd one out? -- https://mail.python.org/mailman/listinfo/python-list