Complex Number Identification

I am creating a calculator application for all types of mathematical algorithms. However, I want to determine if the root is complex, and then has an exception for it. I came up with this:

if x == complex():
    print("Error 05: Complex Root")

However, when the application starts, nothing is identified and printed, knowing what xis the complex root.

+5
source share
5 answers

I am not 100% sure what you are asking, but if you want to check if a variable is a complex type, you can use isinstance . For instance,

x = 5j
if isinstance(x, complex):
    print 'X is complex'

prints

X is complex
+13
source
>>> isinstance(1j, complex)
True
+8
source

:

if isinstance(x, complex):
    print("Error 05: Complex Root")

2 + 0j, 3j, 2, 2.12 ..

, (ValueError TypeError), .

+6

Numpy v1.15 includes a feature: numpy.iscomplex ( x )

where xis the number to be identified.

+1
source

One way to do this might be to do

if type(x) == complex():
    print("Error 05: Complex Root")

As others have already noted, isinstance works too

0
source

All Articles