[Tutor] Fastest (x,y) distance calculation

Raymond Hettinger python at rcn.com
Thu Sep 11 23:39:12 EDT 2003


[Raymond Hettinger]
> > Distance calculations are much cheaper if you store the coordinates
> > as complex numbers and use abs().

[Magnus]
> I tried that, and the distance calculation (pos-tmp.rect)
> got much quicker, but abs() ate up all the improvement. :(

Make sure you set _abs = abs to save the builtin lookup time.
I get a two to one improvement on your code:

  



>>> import timeit
>>> setup = """
class Point:
    pass

p = Point()
p.x = 11.0
p.y = 5.0

q = Point()
q.x = 8.0
q.y = 9.0
r = 8 + 9j

class Temple:
    pass

t = Temple()
t.rect = p
t.complex = 11+5j

_abs = abs
"""

>>> stmt1 = """
distsqrd = (t.rect.x - q.x) ** 2 + (t.rect.y - q.y) **2
"""

stmt2 = """
dist = _abs(t.complex - r)
"""

>>> print timeit.Timer(stmt1, setup).repeat(3)
[6.5299007693726008, 7.4887745352754829, 6.5537052246936742]
>>> print timeit.Timer(stmt2, setup).repeat(3)
[3.1982123401330895, 3.1982919593020362, 3.5620459612128919]

Executive summary:   abs(z1-z2)  beats  the (deltax**2 + deltay**2) approach


Raymond Hettinger




#################################################################
#################################################################
#################################################################
#####
#####
#####
#################################################################
#################################################################
#################################################################



More information about the Tutor mailing list