Python program to Return the real part of the complex argument (original) (raw)
Last Updated : 29 Nov, 2022
Given a complex number, the task is to write a Python Program to return the real part of the complex argument.
What is a Complex number?
Complex numbers are those numbers that are written in the format a+ib, where ‘a’ and ‘b’ are real numbers and ‘i’ is the imaginary part called “iota.” (√-1) is the value of i.
In Python, Imaginary numbers can be created by using the complex() function, and the real part is returned using the .real attribute. In the article, we are using a NumPy array to create imaginary numbers and using the numpy.real() function to get the real component from it.
Method 1:
In this example, we can create a complex number using the complex() function. and return a real number with the help of the .real attribute.
Python3
imaginary_number
=
complex
(
1
+
2j
)
print
(
'Real part of the imaginary number is : '
+
str
(imaginary_number.real))
Output:
Real part of the imaginary number is : 1.0
Method 2:
In this example, we can create a complex number using a NumPy array and return its dimensions, datatype, shape, and real number.
Python3
import
numpy as np
array
=
np.array([
1.
+
2.j
,
2.
+
3.j
,
4.
+
5.j
])
print
(array)
print
(
"The dimension of the array is : "
,array.ndim)
print
(
"Datatype of our Array is : "
,array.dtype)
print
(
"Shape of the array is : "
,array.shape)
print
(
"real part of the imaginary numbers in the array is :"
,np.real(array))
Output:
[1.+2.j 2.+3.j 4.+5.j] The dimension of the array is : 1 Datatype of our Array is : complex128 Shape of the array is : (3,) real part of the imaginary numbers in the array is : [1. 2. 4.]
Method #3: Using slicing
Python3
imaginary_number
=
complex
(
55
-
2j
)
string_imaginaryNumber
=
str
(imaginary_number)
if
(
'+'
in
string_imaginaryNumber):
`` index
=
string_imaginaryNumber.index(
'+'
)
else
:
`` index
=
string_imaginaryNumber.index(
'-'
)
print
(
'Real part of the imaginary number is : '
+
`` str
(string_imaginaryNumber[
1
:index]))
Output
Real part of the imaginary number is : 55