Programming trick: complex numbers in Python

They are not as intuitive to use as one would think.

First, the imaginary unit "j" can't be used alone. "1 + j" must be written "1 + 1j".

Second, the real and imaginary parts are attributes of complex numbers, as in "(1+1j).real", "(1+1j).imag". An AttributeError exception will be raised if these attributes are taken for a noncomplex number. Either catch the exception, or cast the variable to complex before using real and imag.

Third, complex conjugation is a method defined by complex objects, as in "(1+1j).conjugate()". As above, either catch the AttributeError, or cast to complex.

At least Numeric defines the ufunc "conjugate" for arrays, complex or not.

Jan 25, 2005

complex (/progtricks)
2005-01-25, 14:23 [edit]

  Login:   Password:   [rss] [cc] [w3] [css]

© M. Vallisneri 2012 — last modified on 2010/01/29

Tantum in modicis, quantum in maximis