6
$\begingroup$

I have just started programming in Mathematica and still have to get a hang of it (and rule-based programming), so I apologize if this question may seem stupid. I will explain it with a concrete example.

I have an expression which is an inequality, and I have to determine if the unknown variable appears under a square root (the expression might also not contain any square roots at all).

So, my first thought was to use FreeQ:

FreeQ[expr, Sqrt[x]]

The problem occurs when x appears at deeper levels of the expression tree under Sqrt.

For example,

expr = 3 Sqrt[2 x + 9] + 23/ 7 x^2 >= 0

so the FullForm is

GreaterEqual[Plus[..., Times[3, Power[Plus[9, Times[2, x]], Rational[1, 2]]]], 0]

So I can't use Sqrt[___x___] or x_Sqrt as it's head is Times, and not Power.

Is there anyway I can build a pattern to use with FreeQ or is there any other function that can determine if a given expression contains a symbol AFTER a given head (e.g., Power[(something with x), 1/2] as in my case).

$\endgroup$
4
  • 1
    $\begingroup$ Consider Cases[3 Sqrt[2 x + 9] + Sqrt[a + 2] + 23/7 x^2 >= 0, Sqrt[expr_] /; ! FreeQ[expr, x], ∞] $\endgroup$ May 9, 2016 at 11:37
  • $\begingroup$ FreeQ[expr, Power[something : __, Rational[1, 2]] /; Not[FreeQ[something, x]]]? or FreeQ[expr, Sqrt[something : __] /; Not[FreeQ[something, x]]] $\endgroup$
    – kglr
    May 9, 2016 at 11:39
  • $\begingroup$ These work! Thank you very much! $\endgroup$
    – MaggieD
    May 9, 2016 at 11:54
  • 2
    $\begingroup$ Possibly of interest: (5682963) $\endgroup$
    – Mr.Wizard
    May 9, 2016 at 12:21

1 Answer 1

6
$\begingroup$

Here are two ways to do it taken from comments to the question.

kglr and J.M.

With[{expr = 3 Sqrt[2 x + 9] + Sqrt[a + 2] + 23/7 x^2 >= 0}, 
  Cases[expr, Sqrt[something_] /; ! FreeQ[something, x], ∞]]

kglr

With[{expr = 3 Sqrt[2 x + 9] + Sqrt[a + 2] + 23/7 x^2 >= 0}, 
  Cases[expr, Power[something : __, Rational[1, 2]] /; Not[FreeQ[something, x]], ∞]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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