Python complex(): Working with Complex Numbers

The complex() function creates a complex number in Python, which consists of a real part and an imaginary part (denoted as j). This is useful in mathematics, engineering, and scientific computing.

Simple Example

num = complex(3, 4)
print(num)  # Output: (3+4j)

Here, 3 is the real part, and 4j is the imaginary part.

Syntax

complex(real, imaginary)
  • real → The real part (default is 0).
  • imaginary → The imaginary part (default is 0).

You can also create complex numbers from a string:

num = complex("2+5j")
print(num)  # Output: (2+5j)

1. Accessing Real and Imaginary Parts

You can get the real and imaginary parts separately:

num = complex(7, -3)
print(num.real)  # Output: 7.0
print(num.imag)  # Output: -3.0

This is useful when working with complex number operations.

2. Performing Mathematical Operations

Complex numbers support basic math operations:

a = complex(2, 3)
b = complex(1, 4)

print(a + b)  # Output: (3+7j)
print(a * b)  # Output: (-10+11j)

These operations are common in signal processing, physics, and engineering.

3. Using complex() in Scientific Calculations

Python’s cmath module provides advanced functions for complex numbers:

import cmath

num = complex(1, 1)
print(cmath.sqrt(num))  # Output: (1.09868411346781+0.45508986056222733j)

Useful for electrical engineering, quantum mechanics, and fluid dynamics.

4. Using Complex Numbers in SQL & Data Processing

Some databases store complex numbers as strings. Convert them before performing calculations:

db_value = "3+2j"
num = complex(db_value)
print(num * 2)  # Output: (6+4j)

This ensures accurate calculations when retrieving data from databases.

Key Notes

  • Creates complex numbers easily – supports both numeric and string input.
  • Access real and imaginary parts – useful for calculations.
  • Supports mathematical operations – addition, multiplication, etc.
  • Works with cmath for advanced calculations – essential for scientific computing.

By using complex(), you can handle complex numbers efficiently, whether in engineering, physics, or database processing. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top