# How to test if $ⅈ$ is in an expression?

From this answer https://mathematica.stackexchange.com/a/9773/68791 and according to the documentation:

FreeQ[list,form] test whether form occurs nowhere in list

However, I encountered some oddities:

expr = x[0] + (-(1/2) - (I*Sqrt[3])/2)*x[1] + (-(1/2) + (I*Sqrt[3])/2)*x[2];
FreeQ[expr, I]
(* True -- I *is not* in expr whereas it obviously is *)

FreeQ[expr, I/2]
(* False -- I/2 *is* in expr *)


By using TreeForm it seems to me than I/2 is handled as an atom, and not as a compound expression Div[I,2].

How can I reliably test if $$\large ⅈ$$ (or any complex with a non-zero imaginary part) is in an expression?

• How would one treat things like ArcSin[2]? I assume it should be flagged as a nonreal, complex number. – Michael E2 Dec 13 '19 at 4:38

Look at the FullForm. This is what Mathematica actually sees.

expr // FullForm

Plus[x[0],
Times[Plus[Rational[-1, 2],
Times[Complex[0, Rational[-1, 2]], Power[3, Rational[1, 2]]]], x[1]],
Times[Plus[Rational[-1, 2],
Times[Complex[0, Rational[1, 2]], Power[3, Rational[1, 2]]]], x[2]]
]

I/2 // FullForm

Complex[0,Rational[1,2]]


I is really Complex[0, 1] so Mathematica searches for that specifically. If you just want to find a Complex number use FreeQ[_Complex]

If you have to deal with the corner cases where the expression may contain Complex[_, 0.] or Complex[_, 0], you should use FreeQ[Complex[_, n_?(#==0.&)]]

• Isn't there some corner cases where an expression would contain Complex[ _, 0]? – Sylvain Leroux Dec 13 '19 at 2:12
• @SylvainLeroux that can't happen unless stuff is held, but Complex[1, 0.] can. On the other hand, you can catch that with FreeQ[Complex[_, n_?(#==0.&)]]. The bigger point is that you need to think about true form of an expression when pattern matching, not the one you see displayed. – b3m2a1 Dec 13 '19 at 2:14
• It could happen if in Complex[x, 0], x is not a number. E.g. Complex[Sqrt[2], 0]. These forms do not arise from normal arithmetic/algebraic computations done by Mathematica, however. They would have be the result of some explicit construction of a Complex expression (by the user). – Michael E2 Dec 13 '19 at 2:17
• @MichaelE2 interesting! Didn't realize that would happen – b3m2a1 Dec 13 '19 at 2:19
• @SylvainLeroux 0==0. but 0=!=0. – b3m2a1 Dec 13 '19 at 2:27