In Python, a complex number is a number with a real and imaginary part represented by `x + yj`, where `x` is the real part, `y` is the imaginary part, and `j` is the imaginary unit (which satisfies the equation `j^2 = -1`). In this article, I will show you how to create complex number in python with examples.
1. How To Create Complex Number In Python.
- You can create a complex number in Python by using the `complex()` function or by directly writing the number in the form `x + yj`.
- Here are some examples.
1.1 Creating complex numbers using complex().
- Blow example will create 2 complex numbers using the python complex() function.
>>> a = complex(2, 3) >>> b = complex(1, -4) >>> >>> print(a) (2+3j) >>> >>> print(b) (1-4j)
1.2 Creating complex numbers directly.
- You can also use the below python source code to create complex numbers directly.
d = -3.5 + 0j print(c) print(d) # Below is the output. (5+2j) (-3.5+0j)
1.3 Perform arithmetic operations with complex numbers.
- You can perform arithmetic operations with complex numbers in the same way as you do with real numbers.
a = 2 + 3j b = 1 - 4j print(a + b) print(a * b) print(a / b) Below is the above source code output. (3-1j) (14-5j) (-0.5882352941176471+0.6470588235294118j)
1.4 How to access the real and imaginary parts of a complex number.
- In addition, you can access the real and imaginary parts of a complex number using the `real` and `imag` attributes respectively.
a = 2 + 3j print(a.real) print(a.imag) #Below is the above code output. 2.0 3.0