Python complex(): Create Complex Numbers — Syntax, From Floats and Strings, Real/Imag Parts, Conjugate, cmath Integration, Pitfalls, and Practical Examples > dev

Skip to content

Entire search within the site

👈Go back dev

Python Python complex(): Create Complex Numbers — Syntax, From Floats and Str…

page info

name Goposu datetime⏰ 25-10-11 02:41 hit👁️ 13 comment💬 0

text

Python complex(): Create Complex Numbers — Syntax, From Floats and Strings, Real/Imag Parts, Conjugate, cmath Integration, Pitfalls, and Practical Examples

Python complex(): Construct complex numbers from real and imaginary parts

The built-in complex() function creates complex numbers, which represent values on the plane with a real and an imaginary component. Complex numbers are essential for signal processing, control systems, physics simulations, and algorithms involving roots of negative numbers.

Syntax

complex(real=0, imag=0)
complex(string)

Parameters: Provide real and optional imag (both numeric), or a single string in a valid complex format.

Returns: A complex object with attributes .real and .imag.

Quick examples

print(complex(3, 4))     # (3+4j)
print(complex(5))        # (5+0j)
print(complex(0, -2))    # -2j
print(complex("3+4j"))   # (3+4j)
print(complex(" -2j "))  # -2j

Valid string formats

When using a single string, it must be a proper complex literal: optional spaces, a real part, an optional sign, and an imaginary part ending in j. Parentheses are not required. Scientific notation is supported.

print(complex("1.5-2.5j"))     # (1.5-2.5j)
print(complex("+3.2e1-4e-2j")) # (32-0.04j)
# Invalid: two-argument strings or missing 'j'
# complex("3", "4")  # TypeError
# complex("3 + 4")   # ValueError (no 'j')

Access parts and conjugate

Use .real, .imag, and .conjugate() to inspect and transform complex numbers. The conjugate flips the sign of the imaginary part.

z = complex(3, -4)
print(z.real, z.imag)    # 3.0 -4.0
print(z.conjugate())     # (3+4j)

Arithmetic and cmath integration

Complex numbers support standard arithmetic: addition, subtraction, multiplication, division, and exponentiation. Use cmath for complex-aware functions (e.g., sqrt, exp, phase, polar).

import cmath

z1 = complex(1, 2)
z2 = complex(2, -1)
print(z1 + z2)            # (3+1j)
print(z1 * z2)            # (4+3j)
print(cmath.sqrt(-1))     # 1j
print(cmath.phase(3+4j))  # 0.9272952180016122 (radians)
print(cmath.polar(3+4j))  # (5.0, 0.92729...)  (r, theta)

Common use cases

  • Signal processing: Represent phasors and Fourier coefficients.
  • Numerical methods: Solve equations with complex roots.
  • Electromagnetics: Model impedance and wave propagation.
  • Geometry: Rotate points via multiplication by e^{iθ}.
# Rotate a point by theta using Euler's formula
import cmath
theta = cmath.pi / 4
rot = cmath.exp(1j * theta)
p = complex(1, 0)
print(p * rot)  # (0.7071067811865476+0.7071067811865475j)

Pitfalls and caveats

  • String parsing: Only the single-argument string form is allowed; the two-argument form must be numeric.
  • Float precision: Real/imag parts are IEEE-754 doubles; rounding errors apply.
  • NaN/Inf: Complex values may include float('nan') or float('inf') in either part—propagation follows float semantics.
  • Types: Passing non-numeric objects (except a valid literal string) raises TypeError.
print(complex(float('inf'), 1))  # (inf+1j)
print(complex(float('nan'), 0))  # (nan+0j)
# Invalid types
# complex(object())  # TypeError

Formatting and display

Use f-strings and format specifiers for readable output. Access magnitude and angle via abs(z) and cmath.phase(z).

z = 3 + 4j
print(f"z = {z.real:.1f} + {z.imag:.1f}j")   # z = 3.0 + 4.0j
print(f"|z| = {abs(z):.2f}")                 # |z| = 5.00
print(f"arg(z) = {cmath.phase(z):.3f} rad")  # arg(z) = 0.927 rad

FAQ

Is the imaginary unit written as i in Python?
No. Python uses j (e.g., 1j) to denote the imaginary unit.
How do I parse user input like "3+4i"?
Replace i with j and validate: complex(s.replace("i","j")) (handle spaces and invalid formats).
How do I get magnitude and angle?
Use abs(z) for magnitude and cmath.phase(z) for angle; cmath.polar(z) returns both.
Can I create complex numbers from decimals?
Convert to floats first or implement custom numeric types; complex(Decimal('1.2'), Decimal('3.4')) works via coercion to float.

Related keywords

Python complex, imaginary unit j, cmath, polar form, phase, conjugate, magnitude, Euler’s formula, signal processing

👍good0 👎nogood 0

comment list 0

There are no registered comments.

이미지 목록

전체 19건 1 페이지
게시물 검색
Copyright © https://goposu.com All rights reserved.
View PC version