MacPython Logo from __future__ import *

buy music albums Silver Apples buy mp3 albums Tarrus Riley buy tracks mp3 Kravits buy Reaper albums mp3 buy Kravits albums music buy music Evita CD online albums mp3 Silver Apples download Madonna CD music buy tracks music Kravits download music albums Silver Apples

2005-01-29

Another (ab)use for Python’s complex type

Filed under: python — bob @ 7:51 pm

I'm not sure where I saw this first, but it can be convenient to use Python's complex type to represent 2D points or vectors. Adding two complex numbers together is the same operation as adding vectors, and the absolute value of a complex number is equivalent to the norm of the vector (can be used to calculate distance or length).

# The norm of the vector (3.0, 4.0)
>>> abs(3 + 4j)
5.0

# The distance between (8.0, 10.0) and (-5.0, 2.0)
>>> abs((-5 + 2j) - (8 + 10j))
15.264337522473749

# Adding the vectors (5.0, 8.0) and (-3.0, 2.0) to get (2.0, 10.0)
>>> (5 + 8j) + (-3 + 2j)
(2+10j)

# Suggested by Max Thiercy
# Multiplication of a vector (2, 3) by a scalar (5):
>>> a = 2 + 3j
>>> b = 5 * a
(10+15j)

UPDATE: Frederik commented that he had also written on this topic in the context of Tkinter

2 Comments »

  1. More here:

    http://online.effbot.org/2004_09_01_archive.htm#tkinter-complex

    Comment by Fredrik — 2005-01-30 @ 2:43 am

  2. It can’t be an abuse of the Python complex type as, from a mathematical point of view, a complex number IS a two-dimensional vector (technically speaking, there is a bijection between the complex number set, named C, and the cartesian product of the real number set R with itself).

    So you could also add the multiplication of a vector by a scalar (i.e. real number) :
    >>> a = 2 + 3j
    >>> b = 5 * a

    Comment by Max THIERCY — 2005-02-01 @ 10:09 am

RSS feed for comments on this post.

Leave a comment

Protected by WP-Hashcash.

Powered by WordPress