Python Complex to Int
Last Updated :
19 Jan, 2024
In Python, we can work by changing the data types of objects using type conversion or typecasting. Type conversion in Python is of two types – Implicit, where type conversion is automatically performed by Python, and explicit, where we make use of predefined functions to change data types. In this post, we will learn how we can convert a Complex data type to Int in Python, if at all.
Complex Data Type to Int in Python
Note that a complex number has two parts, real and imaginary. We can make use of the real and imag attributes of Python to access the real and imaginary part of a complex data type as float respectively.
Python3
x = 4 + 6j
print (x.real)
print (x.imag)
|
Thus, we will first use the real attribute to change the complex number to a float and then further use the int() function to convert the float data type to an integer. Here is the code for the same:
Python3
x = 4 + 6j
print ( "The given complex number: " , x)
r = x.real
i = int (r)
print ( "The equivalent integer: " , i)
|
Output
The given complex number: (4+6j)
The equivalent integer: 4
Error While Converting Python Complex to Int
To convert a complex number into an integer, we can use the same method of explicit type conversion. However, there is a problem. Look at the code given below.
Here, we are changing an integer data type to a complex data type using the complex() function which works normally as expected.
Python3
x = 4
print (x)
print ( complex (x))
|
However, if we try the opposite of this, that is, if we use the int() data type to change a complex data type to an integer, then we will run into an error:
Python3
x = 4 + 3j
print (x)
print ( int (x))
|
Output
Traceback (most recent call last):
File “Solution.py”, line 8, in <module>
print(int(x))
TypeError: can’t convert complex to int
This happens because we cannot convert a larger data type to a smaller data type since it leads to the loss of data. Naturally, changing a complex to integer will result in the loss of the imaginary part of the number, and thus, this kind of type casting is not supported by Python. The same is true for some other data types as well. As an example, we cannot convert a string to an integer in Python using the int() function. Here is the code for the same:
Output
Traceback (most recent call last):
File “Solution.py”, line 5, in <module>
print(int(x))
ValueError: invalid literal for int() with base 10: ‘GFG’
Thus, we can say that conversion of a complex to integer is not possible in Python. However, if you do not care about the loss of the imaginary part of a complex number, then you can follow some workarounds to get the desired result.
This is essentially how you can convert a complex number to an Integer in Python. Note that there is loss of data even if you follow this workaround, and hence, you should only use this when absolutely necessary.
Share your thoughts in the comments
Please Login to comment...