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
# creating an imaginary number. imaginary_number = complex ( 1 + 2j ) # returning the real part of the # imaginary number 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 # Creating an array of imaginary numbers array = np.array([ 1. + 2.j , 2. + 3.j , 4. + 5.j ]) print (array) # dimension of the array print ( "The dimension of the array is : " ,array.ndim) # Datatype of the array print ( "Datatype of our Array is : " ,array.dtype) # shape of the array is print ( "Shape of the array is : " ,array.shape) # numpy is real() method is used to return the # real part of the imaginary numbers in the array 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
# creating an imaginary number. imaginary_number = complex ( 55 - 2j ) string_imaginaryNumber = str (imaginary_number) # Find the index of positive operator or negative operator # between real and imaginary part if ( '+' in string_imaginaryNumber): index = string_imaginaryNumber.index( '+' ) else : index = string_imaginaryNumber.index( '-' ) # returning the real part of the # imaginary number print ( 'Real part of the imaginary number is : ' + str (string_imaginaryNumber[ 1 :index])) |
Real part of the imaginary number is : 55