0
0
NumPydata~5 mins

Complex number type in NumPy

Choose your learning style9 modes available
Introduction

Complex numbers help us work with values that have a real and an imaginary part. They are useful in many science and engineering problems.

When dealing with electrical circuits that use alternating current.
When analyzing waves or signals in physics or engineering.
When solving equations that have no real number solutions.
When working with Fourier transforms in data analysis.
When modeling rotations and oscillations in 2D space.
Syntax
NumPy
numpy.complex64
numpy.complex128

# Create a complex number array:
np.array([1+2j, 3+4j], dtype=np.complex64)

Use complex64 for single precision complex numbers (real and imaginary parts are 32-bit floats).

Use complex128 for double precision complex numbers (real and imaginary parts are 64-bit floats).

Examples
This creates a numpy array of complex numbers with single precision.
NumPy
import numpy as np
z = np.array([1+2j, 3+4j], dtype=np.complex64)
print(z)
This creates a single complex number with double precision.
NumPy
z = np.complex128(5 + 6j)
print(z)
This creates a complex array by adding real and imaginary parts separately.
NumPy
z = np.array([1, 2, 3]) + 1j * np.array([4, 5, 6])
print(z)
Sample Program

This program creates an array of complex numbers, then finds their magnitudes and angles. Magnitude tells how far the number is from zero, and angle tells the direction.

NumPy
import numpy as np

# Create a complex array
z = np.array([2+3j, 4+5j, 6+7j], dtype=np.complex128)

# Calculate the magnitude (absolute value) of each complex number
magnitudes = np.abs(z)

# Calculate the angle (phase) of each complex number
angles = np.angle(z)

print("Complex numbers:", z)
print("Magnitudes:", magnitudes)
print("Angles (radians):", angles)
OutputSuccess
Important Notes

Complex numbers in numpy always have a real and imaginary part stored as floats.

Use np.abs() to get the magnitude and np.angle() to get the angle of complex numbers.

Complex numbers can be used in many math functions like addition, multiplication, and more.

Summary

Complex numbers have a real and an imaginary part.

Use numpy's complex64 or complex128 to work with complex numbers.

You can find magnitude and angle using np.abs() and np.angle().