complex
The built-in complex
data type provides support for complex numbers, which are essential in mathematical computations involving two-dimensional vector arithmetic, sound frequency analysis, and fractal generation. Here’s a quick example of creating a complex number using literals and accessing its values:
>>> z = 3 + 2j
>>> z.real
3.0
>>> z.imag
2.0
complex
Constructors
complex(real=0, imag=0)
complex(string)
Arguments
Argument | Description | Default Value |
---|---|---|
real |
The real component of the complex number. | 0 |
imag |
The imaginary component of the complex number. | 0 |
string |
A string representation of a complex number, which can include both real and imaginary components | Required argument |
Return Value
- Returns a Python
complex
object
complex
Examples
Creating an empty instance of a complex number:
>>> z = complex()
>>> z
0j
Creating instances using literals:
>>> x = 3 + 2j
>>> x
(3+2j)
>>> y = 3.14 + 0j
>>> y
(3.14+0j)
>>> z = 0 + 2.71j
>>> z
2.71j
Creating an instance using the class constructor:
>>> z = complex(3, 2)
>>> z
(3+2j)
Accessing the components of a complex number:
>>> z.real
3.0
>>> z.imag
2.0
complex
Methods
Method | Description |
---|---|
.conjugate() |
Returns the complex conjugate of the number |
complex
Common Use Cases
The most common use cases for the complex
data type include:
- Performing mathematical calculations involving complex numbers
- Representing two-dimensional vectors
- Conducting frequency analysis in sound engineering
- Generating fractals such as the Mandelbrot set
complex
Real-World Example
Say that you need to calculate the distance between two points on the complex plane, representing them as complex numbers:
>>> point1 = complex(1, 2)
>>> point2 = complex(4, 6)
>>> distance = abs(point2 - point1)
>>> distance
5.0
In this example, complex numbers allow us to treat points as vectors, and the abs()
function computes the distance between these points, showcasing the practical use of complex numbers in geometry.
Related Resources
Tutorial
Simplify Complex Numbers With Python
In this tutorial, you'll learn about the unique treatment of complex numbers in Python. Complex numbers are a convenient tool for solving scientific and engineering problems. You'll experience the elegance of using complex numbers in Python with several hands-on examples.
For additional information on related topics, take a look at the following resources:
- How to Find an Absolute Value in Python (Tutorial)
- Numbers in Python (Tutorial)
- The Python math Module: Everything You Need to Know (Tutorial)
- Exploring the Python math Module (Course)