1
$\begingroup$

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].

enter image description here

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

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

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.&)]]

| improve this answer | |
$\endgroup$
  • $\begingroup$ Isn't there some corner cases where an expression would contain Complex[ _, 0]? $\endgroup$ – Sylvain Leroux Dec 13 '19 at 2:12
  • $\begingroup$ @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. $\endgroup$ – b3m2a1 Dec 13 '19 at 2:14
  • 3
    $\begingroup$ 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). $\endgroup$ – Michael E2 Dec 13 '19 at 2:17
  • $\begingroup$ @MichaelE2 interesting! Didn't realize that would happen $\endgroup$ – b3m2a1 Dec 13 '19 at 2:19
  • 2
    $\begingroup$ @SylvainLeroux 0==0. but 0=!=0. $\endgroup$ – b3m2a1 Dec 13 '19 at 2:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.