[pygame] Re: [Tutor] Fastest (x,y) distance calculation

Bob Ippolito bob at threeoh.com
Fri Sep 12 16:25:22 EDT 2003


On Friday, Sep 12, 2003, at 16:01 America/New_York, Zak Arntson wrote:

>> [Raymond Hettinger]
>>>> Distance calculations are much cheaper if you store the coordinates
>>>> as complex numbers and use abs().
>
> I don't know the concept behind using complex numbers and abs to 
> determine
> distance. How does that work?

You can think of complex numbers as a 2D plane in a lot of respects.  
The imaginary component is the Y axis, and the real component is the X 
axis.  abs(c) is defined as the distance from the origin complex(0, 0j) 
or math.sqrt(c.real**2 + c.imag**2).

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

But does creating two complex numbers out of two integer pairs add more 
overhead than the (deltax*deltax + deltay*deltay) version?  I don't 
think it's faster unless MAYBE you store the coordinates as complex 
numbers internally at all times.  The math.hypot(deltax, deltay) 
version is probably faster in practice.

In any case, you're doing more computational work with abs or hypot 
because they are the actual distance, not the distance**2.

-bob




More information about the Tutor mailing list