11

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.

  • Are the indents exactly as in your question? Is there any error? Could you add `else` part of `if` statement? What about `complex()`? Shouldn't you pass an argument to it and return `True` or `False`? – Tadeck Mar 21 '12 at 23:57
  • 2
    Wait a second - what if a complex root is not an error? Sometimes that's the right answer. Are you sure it should be flagged as an error? – duffymo Mar 22 '12 at 00:02

5 Answers5

28

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
Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
9
>>> isinstance(1j, complex)
True
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
9

Try this:

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

This prints error for 2 + 0j, 3j, but does not print anything for 2, 2.12 etc.

Also think about throwing an error (ValueError or TypeError) when the variable is complex.

Tadeck
  • 132,510
  • 28
  • 152
  • 198
5

In NumPy v1.15, a function is included: numpy.iscomplex(x)

where x is the number, that is to be identified.

0

One way to do it could be to do,

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

As others have pointed out, isinstance works too

Evelyn
  • 85
  • 8