Language: EN

numeros-complejos-en-python

Complex Numbers in Python

In Python, complex numbers are represented using the form a + bj, where a and b are real numbers, and j is the imaginary unit (√-1). Complex numbers in Python are useful in mathematics, engineering, and other disciplines where calculations with square roots of negative numbers are needed.

Complex numbers in Python can be declared using the complex() function or directly using the a + bj notation:

complex_number1 = complex(1, 2)
print(complex_number1)  # Output: (1+2j)

complex_number2 = 3 + 4j
print(complex_number2)  # Output: (3+4j)

It is possible to access the real and imaginary parts of a complex number using the .real and .imag attributes, respectively:

number = 1 + 2j
real_part = number.real
imaginary_part = number.imag
print(real_part, imaginary_part)  # Output: 1.0 2.0

Python uses the standard representation of complex numbers according to the IEEE 754 standard for double-precision floating-point numbers.

Operations with Complex Numbers

Python supports several mathematical operations with complex numbers, including addition, subtraction, multiplication, division, and other operations specific to complex numbers.

Basic operations behave as expected for complex numbers:

# Addition
sum_result = (1 + 2j) + (3 + 4j)
print(sum_result)  # Output: (4+6j)

# Subtraction
subtraction = (5 + 6j) - (2 + 1j)
print(subtraction)  # Output: (3+5j)

# Multiplication
multiplication = (2 + 3j) * (4 + 5j)
print(multiplication)  # Output: (-7+22j)

# Division
division = (5 + 6j) / (2 + 1j)
print(division)  # Output: (4+1j)

Python also provides functions and methods to work with complex numbers, such as the conjugate (conjugate()), magnitude (abs()), and argument (phase()):

# Conjugate
number = 3 + 4j
conjugate = number.conjugate()
print(conjugate)  # Output: (3-4j)

# Magnitude
magnitude = abs(number)
print(magnitude)  # Output: 5.0 (square root of 3^2 + 4^2)

# Argument (phase)
argument = cmath.phase(number)
print(argument)  # Output: 0.9272952180016122 (in radians)

Conversion Between Types

It is possible to convert other data types to complex numbers using the complex() function:

# Conversion from integers
integer_number = 5
complex_number = complex(integer_number)
print(complex_number)  # Output: (5+0j)

# Conversion from floats
float_number = 3.14
complex_number = complex(float_number)
print(complex_number)  # Output: (3.14+0j)