Complex numbers in python

Each Answer to this Q is separated by one/two green lines.

Are complex numbers a supported data-type in python? If so, how do you use them?

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
>>> 1J
>>> 1j * 1j

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
>>> z.imag
>>> z.conjugate()

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
>>> pow(3 + 4j, 2)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)

The following example for complex numbers should be self explanatory including the error message at the end

>>> x=complex(1,2)
>>> print x
>>> y=complex(3,4)
>>> print y
>>> z=x+y
>>> print x
>>> print z
>>> z=x*y
>>> print z
>>> z=x/y
>>> print z
>>> print x.conjugate()
>>> print x.imag
>>> print x.real
>>> print x>y

Traceback (most recent call last):
  File "<pyshell#149>", line 1, in <module>
    print x>y
TypeError: no ordering relation is defined for complex numbers
>>> print x==y

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.