To totally unlock this section you need to Log-in
To convert int to complex in python, you can use complex() class with the int passed as an argument to it or add imaginary part to the integer so that the variable would typecast implicitly to complex datatype.
Let's take note that complex numbers are mostly used in geometry, calculus and scientific calculations.
Usually, we can find easily the type of a number in Python, like in the following way: we need just use the type() function:
x = 10 y = 10.55 z = 1 + 2j print(type(x)) print(type(y)) print(type(z)) <class 'int'> <class 'float'> <class 'complex'>
Example 1: Typecasting Int value to Complex
As we already know, a complex number contains two part – real and imaginary. The imaginary part is written with the j suffix.
We can also use the complex() function to create a complex number. We can pass two ints (integer numbers) arguments to the complex() function. The first argument is the real part and the second argument is the complex part.
In this example, we will take an int, print it and its type, convert it to complex type and the print the result.
a = 5 print(a,'is of type:',type(a)) a = complex(a) print(a,'is of type:',type(a)) x = complex(-2, -3.75) print(x) print(x,'is of type:',type(x)) 5 is of type: <class 'int'> (5+0j) is of type: <class 'complex'> (-2-3.75j) is of type: <class 'complex'>
Example 2: Another way to cast Int variable to Complex datatype
You can always add a 0 imaginary part and python promotes the variable to the higher type, which in this case from int to complex.
a = 5 print(a,'is of type:',type(a)) a = a + 4j print(a,'is of type:',type(a)) 5 is of type: <class 'int'> (5+4j) is of type: <class 'complex'>
We can get the real part of the complex number using the real property. We can get the imaginary part of the complex number using the imag property.
a = 3 + 8j print(c.real) # real part print(c.imag) # imaginary part