[Tutor] Fastest (x,y) distance calculation [complex numbers are points in 2d space]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Sep 12 16:54:23 EDT 2003



On Fri, 12 Sep 2003, 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?


Hi Zak,


Complex numbers can be plotted as if they were 2d points.  This is
actually one of the major ideas in math, and it's cool because it grounds
complex numbers in something that most people are familiar with: the 2d
cartesian plane.


Just as regular numbers, like -3 and 3, can be plotted on a number line:

        <--.--+--.-->
         (-3) 0 (3)



Complex numbers, like (3+1j) and (-3-1j), can be plotted on a cartesian
graph:

              y
              ^
              |   . (3+1j)
              |
        <-----+----->x
     (-3-1j)  |
          .   |
              v


When we look at complex numbers this way, the x axis stands for the first
"real" component, and the y axis stands for the second "imaginary"
component.  So complex numbers aren't really so complex: you know about
them already.  *grin*



The "absolute value" of a complex number is defined to be that number's
distance from the "origin".  Just as we can take the absolute value of
normal everyday numbers:

###
>>> abs(3)
3
>>> abs(-3)
3
###


we can also take the abs() of complex numbers:

###
>>> abs(3+1j)
3.1622776601683795
>>> abs(-3-1j)
3.1622776601683795
###

and this, too, shows that abs() is the distance from (0,0).



Another neat thing about complex numbers is that multiplying them has a
real meaning: if we multiply one point by a complex number of length one,
the end result is a rotation of that point!

###
>>> unit = (0.707 + 0.707j)          ## represents a 45 degree angle
>>> abs(unit)
0.99984898859777815                  ## ... well, close enough to one.
                                     ## *grin*
>>>
>>>
>>> p = (1+1j)                       ## p represents the point (1,1)
>>>
>>> p * unit                         ## (1,1) is rotated along (0, 0)
1.4139999999999999j                  ## by 45 degrees!  This shows that
                                     ## the rotated point is at (0, 1.414)
>>>
>>> p * unit * unit
(-0.99969799999999986+0.99969799999999986j)
>>>
>>> p * unit * unit * unit
>>>
(-1.4135729719999997+0j)
>>>
>>> p * unit * unit * unit * unit
(-0.99939609120399975-0.99939609120399975j)
###

(Mathworld talks about how complex numbers are multiplied:
http://mathworld.wolfram.com/ComplexMultiplication.html)


Ok, there's a little bit of numerical inaccuracy showing up, but I hope
the main ideas are clear.



Hope this helps!




More information about the Tutor mailing list