Python built-in Method - complex()
The complex()
method is a built-in function in Python that returns a complex number from a real and an imaginary component.
Here is the syntax for complex()
method:
complex([real[, imag]])Sourcwww:e.theitroad.com
where:
real
: a numeric value that represents the real part of the complex number. Ifreal
is not provided, it defaults to0
.imag
: a numeric value that represents the imaginary part of the complex number. Ifimag
is not provided, it defaults to0
.
Both real
and imag
can be integer or float values, or they can be represented as a string. If a string is used, it must contain a numeric value, optionally followed by the letter 'j' to indicate that the value is imaginary.
Here are some examples of how to use complex()
:
# create a complex number with real and imaginary components z1 = complex(2, 3) print(z1) # (2+3j) # create a complex number with only a real component z2 = complex(4) print(z2) # (4+0j) # create a complex number with only an imaginary component z3 = complex('3j') print(z3) # 3j # create a complex number from a string with both real and imaginary components z4 = complex('4+5j') print(z4) # (4+5j)
In the first example, z1
is a complex number with real component 2
and imaginary component 3
. In the second example, z2
is a complex number with real component 4
and imaginary component 0
. In the third example, z3
is a complex number with real component 0
and imaginary component 3
. In the fourth example, z4
is a complex number with real component 4
and imaginary component 5
.
The complex()
method is useful for performing mathematical operations that involve complex numbers, such as signal processing, control systems, and physics.