Identifying a complex number

user1786283 picture user1786283 · Mar 22, 2012 · Viewed 20k times · Source

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

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

However, nothing is identified or printed when I run the app, knowing that x is a complex root.

Answer

Adam Mihalcin picture Adam Mihalcin · Mar 22, 2012

I'm not 100% sure what you're asking, but if you want to check if a variable is of complex type you can use isinstance. For example,

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

prints

X is complex