Python Reference ยท Built-in Functions
Python complex() function
Reference for Python complex(): create complex numbers from real and imaginary parts or a string, use .real, .imag and conjugate(), and avoid the spaces trap.
The built-in complex type represents a number with a real part and an imaginary part, both stored as floats. Python writes the imaginary unit as j, so 3+4j is a complex literal. Calling complex() builds one from two numbers or from a string.
Complex numbers are used in signal processing, electrical engineering, fractals and anywhere square roots of negative numbers appear. The cmath module provides math functions for them.
z = complex(3, 4) # (3+4j)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
complex() complex(real) complex(real, imag) complex(string)
| Name | Description |
|---|---|
real |
Real part. Can be an int, float or another complex number. Default 0. |
imag |
Imaginary part, same types. Default 0. |
string |
A string like "3+4j". If a string is given, no second argument is allowed. |
Return value: a complex number, equal to real + imag*1j.
Raises: ValueError for a malformed string (including spaces around the + or -); TypeError for unsupported types or when a string is combined with a second argument.
Usage notes
- Attributes and methods.
z.realandz.imagare floats;z.conjugate()flips the sign of the imaginary part. - Magnitude.
abs(z)returns the distance from the origin as a float. - No ordering. Complex numbers cannot be compared with
<or>; only==and!=work. - Literals.
4jis a literal;jalone is a variable name. Write1jfor the imaginary unit. - Strings. The text form is strict:
"1+2j"works,"1 + 2j"does not. Leading and trailing spaces are fine. - Float precision. Parts are 64-bit floats, so results show rounding, as with any float.
- Math functions.
math.sqrt(-1)raisesValueError; usecmath.sqrt(-1), which returns1j.(-1) ** 0.5also returns a complex number. - Polar form.
cmath.polar(z)returns(r, phi), andcmath.rect(r, phi)goes back.
Related
abs(),float(),int(),pow()- Lessons: Numbers, Arithmetic operators, Math and random