PythonPython Variables and Data TypesPython data types
What is a complex number in Python?
Question 34 of 88 · Updated
On this page
- 1. Creating a complex number
- 2. Complex numbers versus integers and floats
- 3. Arithmetic with complex numbers
- 4. Conjugate and magnitude
- 5. Rectangular and polar representation
- 6. The cmath module
- 7. Mixed arithmetic, equality and truthiness
- 8. Precision and approximate equality
- 9. Practical example: rotate points by 90 degrees
- 10. Practical example: serializing a complex number
- 11. Common errors and troubleshooting
- 12. Frequently asked interview questions
- Why does Python use j rather than i?
- Are complex numbers mutable?
- What is the difference between abs(z) and z.real?
- Is a complex number with zero imaginary part equal to a real number?
- Can complex numbers be dictionary keys?
- Are complex numbers always exact?
- Interview-ready answer
- Key takeaways
- Official references
A complex number in Python is a numeric object with a real component and an imaginary component, represented by the built-in complex type. Mathematically, a complex number has the form a + bi, where i squared equals -1. Python uses j instead of i in imaginary literals.
For example, 3 + 4j represents a complex number with real part 3 and imaginary part 4. Complex numbers are useful for signal processing, electrical engineering, mathematical simulations, control systems and two-dimensional transformations.
Python supports complex arithmetic directly, without needing a third-party package.
1. Creating a complex number#
You can create a complex number with an imaginary literal or the built-in complex constructor.
PYTHONz = 3 + 4j print(z.real, z.imag, type(z).__name__) print(complex(3, 4), complex('3+4j'))
Output:
3.0 4.0 complex
(3+4j) (3+4j)| Expression | Meaning |
|---|---|
| 3 + 4j | A complex value with real part 3 and imaginary part 4 |
| 4j | A purely imaginary value |
| 1j | The imaginary unit |
| complex(3, 4) | Construct a complex value from two real numeric arguments |
| complex('3+4j') | Parse a supported complex-number string |
| complex(5) | Convert a real number into a complex value with zero imaginary part |
The real and imag attributes return floating-point components, even when the source literals are integers. Complex objects are immutable; assigning another value to z rebinds the name rather than editing its original object.
The expression 3 + 4j combines a real integer literal, an addition operator and an imaginary literal. A bare j is an ordinary identifier, not a predefined imaginary constant. Write 1j when you mean the imaginary unit.
The string constructor follows its own supported grammar. For instance, complex('3+4j') succeeds, whereas complex('3 + 4j') raises ValueError because of the internal spaces. Do not use eval to parse user-supplied numbers.
2. Complex numbers versus integers and floats#
| Type | Example | Representation and purpose |
|---|---|---|
| int | 5 | Exact whole number, with arbitrary precision subject to resources |
| float | 5.5 | Finite-precision real number |
| complex | 3 + 4j | Pair of floating-point real and imaginary components |
Complex numbers extend ordinary real arithmetic into a two-dimensional numerical plane. Unlike a float, a complex number does not represent a single ordered real quantity.
The two components have the same finite-precision limitations discussed in the preceding integer-versus-float lesson. Creating a complex object from a sufficiently large integer may lose precision or raise an overflow error.
3. Arithmetic with complex numbers#
Python supports addition, subtraction, multiplication, true division and exponentiation for complex numbers.
PYTHONa = 3 + 4j b = 1 - 2j print(a+b, a-b, a*b, a/b)
Output:
(4+2j) (2+6j) (11-2j) (-1+2j)Addition and subtraction operate on corresponding components. For multiplication, use the fact that j squared is -1:
- Real component of the product: a*c - b*d.
- Imaginary component of the product: a*d + b*c.
Here a + bj and c + dj are the two operands. For example, multiplying (3 + 4j) by (1 - 2j) gives real component 3*1 - 4*(-2) = 11 and imaginary component 3*(-2) + 4*1 = -2.
Mathematically, division by a nonzero complex number can be understood by multiplying numerator and denominator by the denominator's conjugate. Python's runtime implements complex division; manual implementations using squared magnitudes can introduce numerical overflow or underflow.
Floor division and modulo are not defined for ordinary Python complex operands. Division by 0j raises ZeroDivisionError.
4. Conjugate and magnitude#
The conjugate of a + bj is a - bj. The magnitude (or modulus) is the distance of the number from the origin in the complex plane.
For z = a + bj, its mathematical magnitude is the square root of a squared plus b squared.
PYTHONz = 3 + 4j print(z.conjugate(), abs(z), z*z.conjugate())
Output:
(3-4j) 5.0 (25+0j)The conjugate flips the sign of the imaginary component. Multiplying a complex number by its conjugate gives its squared magnitude mathematically. For finite-precision inputs, the computed product is subject to rounding and range limits.
Use abs(z) to calculate the magnitude rather than assuming that directly squaring both components and adding them is numerically robust. abs returns a float for ordinary complex inputs.
A complex number with imaginary component zero is still an object of type complex.
5. Rectangular and polar representation#
A complex number can be represented as a point in a plane, with its real component on the horizontal axis and imaginary component on the vertical axis.
Rectangular representation describes the point by its two components. Polar representation describes it by its magnitude r and phase angle theta, measured in radians relative to the positive real axis.
For 3 + 4j, the magnitude is 5 and the phase is approximately 0.927 radians. The two representations describe the same mathematical point; converting between them with floating-point arithmetic can introduce small rounding differences.
PYTHONimport cmath, math z = 3+4j r, theta = cmath.polar(z) print(round(r, 3), round(theta, 3)) print(cmath.isclose(cmath.rect(r, theta), z))
Output:
5.0 0.927
TrueThe cmath.phase function returns the phase directly. The cmath.rect function reconstructs a complex value from its polar coordinates, using cosine and sine of the supplied angle.
Use math.degrees to convert a phase in radians to degrees when needed for display. The numerical phase returned by cmath follows its documented principal-angle convention.
At zero magnitude, a geometric direction is not uniquely defined; do not treat the numerical phase of a zero-valued signal as a meaningful measurement of direction.
6. The cmath module#
Python's standard-library math module provides primarily real-valued mathematical operations. The cmath module provides mathematical functions suitable for complex arguments.
PYTHONimport cmath print(cmath.sqrt(-9)) print(cmath.isclose(cmath.exp(1j*cmath.pi), -1+0j, abs_tol=1e-12))
Output:
3j
TrueThe first result is the principal complex square root of -9. In contrast, math.sqrt(-9) raises ValueError in ordinary Python.
The second example evaluates Euler's identity numerically: e raised to i times pi equals -1 mathematically. A tolerance comparison is appropriate because floating-point sine and cosine calculations can introduce a small imaginary residual.
| Function | Purpose |
|---|---|
| cmath.sqrt(z) | Principal complex square root |
| cmath.exp(z) | Complex exponential |
| cmath.log(z) | Complex logarithm |
| cmath.sin(z), cmath.cos(z) | Complex trigonometric functions |
| cmath.phase(z) | Principal phase angle |
| cmath.polar(z) | Magnitude and phase |
| cmath.rect(r, theta) | Convert polar coordinates to a complex number |
| cmath.isclose(a, b) | Approximate numerical equality |
Some mathematical functions have multiple possible complex values. The standard-library functions return values according to their documented principal branches and branch-cut conventions. For example, the sign of a zero imaginary component can matter when approaching a branch cut.
7. Mixed arithmetic, equality and truthiness#
PYTHONprint(2+3j+5, (2+3j)*0.5) print(3+0j == 3, bool(0j), bool(1j))
Output:
(7+3j) (1+1.5j)
True False TruePython supports mixed arithmetic between compatible built-in numeric types. A real integer or float can participate in complex arithmetic as a value whose imaginary component is zero.
Complex equality compares numerical values, so 3 + 0j compares equal to 3. A complex number is false in Boolean contexts when both components are zero; otherwise it is truthy.
Unlike real numbers, complex numbers do not have a natural total numerical ordering. Python does not support ordinary less-than or greater-than comparisons between complex numbers. Sorting complex values without an explicit ordering criterion therefore fails when such comparisons are required.
If a problem specifically requires sorting by magnitude, a suitable key is abs. If the problem requires lexicographic ordering by components, define that explicitly instead. These are application-specific ordering choices, not intrinsic complex-number ordering.
8. Precision and approximate equality#
PYTHONimport cmath print((0.1+0.2j)+(0.2+0.1j) == 0.3+0.3j) print(cmath.isclose((0.1+0.2j)+(0.2+0.1j), 0.3+0.3j))
Output:
False
TrueBoth components use floating-point arithmetic. Decimal fractions such as 0.1 and 0.2 are not represented exactly on typical binary floating-point systems.
cmath.isclose compares the magnitude of the difference against relative and absolute tolerance criteria. Select tolerances appropriate to the units and error budget of the calculation. Approximate equality is not a general substitute for exact equality, and it need not be transitive.
Complex objects can also contain non-finite floating-point components.
PYTHONimport cmath print(cmath.isfinite(complex(3,4)), cmath.isinf(complex(float('inf'),0)), cmath.isnan(complex(float('nan'),0)))
Output:
True True TrueValidate finite inputs when a numerical application cannot meaningfully handle infinity or NaN. A finite complex value has finite real and imaginary components.
9. Practical example: rotate points by 90 degrees#
A two-dimensional point (x, y) can be represented as x + yj. Multiplying by 1j rotates that point counterclockwise by 90 degrees around the origin:
(x + yj) * j = -y + xj.
PYTHONpoints = [1+0j, 2+1j, -1+2j] rotated = [point * 1j for point in points] print([(int(z.real), int(z.imag)) for z in rotated])
Output:
[(0, 1), (-1, 2), (-2, -1)]For example, (2, 1) becomes (-1, 2). The integer conversions in the display are suitable for these small exact integral coordinates; they should not be applied indiscriminately to fractional or large coordinates.
For n points, this example performs O(n) fixed-size complex arithmetic operations and uses O(n) additional storage for the rotated collection and displayed coordinate pairs. The cost model assumes ordinary built-in complex values with bounded-size floating-point components.
For arbitrary-angle rotation, a unit complex factor can be constructed with cmath.rect(1, theta). This technique is useful in simulations and geometry, although floating-point rounding accumulates during repeated transformations. For large numerical arrays, consider appropriate vectorized numerical tools and benchmark the actual workload.
10. Practical example: serializing a complex number#
The standard JSON data model has no native complex-number type. A Python complex object must be converted to a supported representation before using the standard json encoder without a custom serialization hook.
PYTHONimport json z = 3+4j encoded = json.dumps({'real': z.real, 'imag': z.imag}) print(encoded) parts = json.loads(encoded) print(complex(parts['real'], parts['imag']) == z)
Output:
{"real": 3.0, "imag": 4.0}
TrueThis example defines an explicit object representation with real and imaginary fields. A production API should document that schema and validate field types, finite-value constraints and numeric range.
For strict JSON serialization of floating-point data, consider allow_nan=False when encoding and reject non-finite values during parsing and validation. JSON implementations and downstream numerical consumers may have different precision and range limits.
11. Common errors and troubleshooting#
| Mistake | Correct approach |
|---|---|
| Writing a bare j or mathematical i as an imaginary literal | Use 1j or another imaginary literal |
| Calling math.sqrt on a negative real argument when a complex root is intended | Use cmath.sqrt |
| Comparing complex numbers with less-than or greater-than | Define an ordering criterion, such as magnitude |
| Calling int(z) or float(z) on a complex object | Explicitly inspect or validate z.real and z.imag |
| Expecting exact decimal arithmetic | Account for floating-point precision |
| Dividing by zero complex value | Check the denominator and handle ZeroDivisionError |
| Serializing a complex object directly as JSON | Define a suitable representation |
The following seven expressions were tested independently to confirm their expected failures:
PYTHONimport math import json (1+2j) < (2+3j) # TypeError int(3+0j) # TypeError float(3+0j) # TypeError complex("3 + 4j") # ValueError (1+2j) / 0j # ZeroDivisionError math.sqrt(-9) # ValueError json.dumps(1j) # TypeError
Run each expression separately or handle its exception; an uncaught exception stops normal sequential execution.
Even if the imaginary component is zero, int and float do not directly accept ordinary complex objects. If your application requires conversion to a real value, first check that the imaginary component satisfies the required zero or tolerance policy, then extract the real component. This avoids silently discarding information.
12. Frequently asked interview questions#
Why does Python use j rather than i?#
Python's imaginary literal syntax uses j or J, consistent with a convention used in engineering. The mathematical meaning is the same as i.
Are complex numbers mutable?#
No. Built-in complex objects are immutable. Their real and imaginary components are read-only attributes.
What is the difference between abs(z) and z.real?#
abs(z) returns the magnitude, while z.real returns the horizontal real component. For 3 + 4j these are 5.0 and 3.0 respectively.
Is a complex number with zero imaginary part equal to a real number?#
It can be numerically equal, for example 3 + 0j == 3, but its type is still complex.
Can complex numbers be dictionary keys?#
Yes, built-in complex objects are hashable. Numeric values that compare equal must have equal hashes, so numerically equal int, float and complex keys can refer to the same dictionary entry. Special NaN values require careful handling because their equality behaviour differs.
Are complex numbers always exact?#
No. Their components use floating-point representation, so rounding, overflow, underflow and special values are relevant.
Interview-ready answer#
A complex number in Python is a built-in immutable numeric object represented by a real and an imaginary floating-point component. It can be created using a literal such as 3 + 4j or complex(3, 4). Python supports complex addition, subtraction, multiplication, division and exponentiation. Use the real and imag attributes to inspect the components, conjugate() to obtain the conjugate, abs() for the magnitude, and cmath for complex mathematical functions and polar conversions. Complex numbers support equality but not intrinsic ordering comparisons. They are especially useful in signal processing, electrical engineering and two-dimensional mathematical transformations.
Key takeaways#
- Python uses j in imaginary literals, with 1j representing the imaginary unit.
- Complex values contain two floating-point components and are immutable.
- Rectangular and polar representations describe the same complex value.
- Use cmath for complex-valued mathematical functions and approximate comparisons.
- Choose explicit policies for ordering, conversion, non-finite values and serialization.
Official references#
- Python Language Reference — Imaginary literals
- Python Standard Library — Numeric types
- Python Standard Library — complex constructor
- Python Standard Library — cmath
- Python Tutorial — Floating-Point Arithmetic
- Python Standard Library — json
Verification note: Ten runnable examples and seven expected-exception tests passed locally on CPython 3.13.5. The Mermaid flowchart was manually reviewed for standard syntax and meaningful labels; no local Mermaid parser was available. Official reference links are supplied under the authorised offline research exception. Live documentation and public-site rendering were not checked.
References
- 1.Python Language Reference — Imaginary literalsdocs.python.org
- 2.Python Standard Library — Numeric typesdocs.python.org
- 3.Python Standard Library — complex constructordocs.python.org
- 4.Python Standard Library — cmathdocs.python.org
- 5.Python Tutorial — Floating-Point Arithmeticdocs.python.org
- 6.Python Standard Library — jsondocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design