# Force function to make assumptions about its input variables in Mathematica

I'm trying to force a Mathematica function to make an assumption about its input variables. In my case, I'm trying to define a function to return the pdf of a Gaussian. But let's use a simple toy case:

n[x_]:= x^(1/2);


Thus, n[x] returns

Sqrt[x]


However, n[x^2] returns

Sqrt[x^2]


While this is correct and fine in principle, in my case some of the variables (like variance) will always be positive and will always be real, thus the simplification

n[x^2] = x


is appropriate. I've tried many things like:

n[x_/; x > 0 && Element[x,Reals]]:=x^(1/2);
n[x_]:=Assuming[x > 0 && Element[x,Reals],FullSimplify[x^(1/2)]];


etc. The best I can get it to do is

n[x^2] = Abs[x];


When I want

n[x^2] = x;


Anyone have any advice on how to do this?

-

## migrated from stackoverflow.comApr 9 '12 at 17:38

The following just works:

Assuming[x > 0, Simplify[Sqrt[x^2]]]

(*
==> x
*)


n[x_/; x > 0 && Element[x,Reals]]:=x^(1/2);
n[x_]:=Assuming[x > 0 && Element[x,Reals],FullSimplify[x^(1/2)]];


doesn't work because the x that is passed after a call of n[x^2] isn't x but x^2. So you're assuming x^2>0 or Element[x^2,Reals].

-

Just to note there is a simple approach to this. You could define your function a bit differently:

n[x_] := PowerExpand[x^(1/2)]


which assumes that x is real and positive and gives:

n[x^2]


x

Alternatively you can keep general:

n[x_] := x^(1/2)


But in calculations when need real-positive assumption on x use

PowerExpand[n[x^2]]


x

Function PowerExpand takes Assumptions option which allow to do some neat stuff:

PowerExpand[Sqrt[z^2], Assumptions -> z < 0]


-z

or with Assumptions->True, PowerExpand gives a universally correct expansion formula:

PowerExpand[Sqrt[z^2], Assumptions -> True]


E^(I [Pi] Floor[1/2 - Arg[z]/[Pi]]) z

-

Here's a function which assumes that every symbol in the expression passed to it which is used as non-head is positive. Note however that this might not always be what you want.

n[x_]:=Assuming[And@@(#>0&/@Union@Cases[x,_Symbol,Infinity]),Simplify[x^(1/2)]]


With this definition, you get

n[a^2]
(*
==> a
*)


It works as follows:

Cases[x,_Symbol,Infinity] gives a list of all symbols in the expression passed through x, ignoring heads (so Cases[Sin[omega*t],_Symbol,Infinity] gives {omega,t}, not {Sin,Times,omega,t}). Applying Union to the result just is there to delete duplicates (strictly speaking it is not necessary). By mapping #>0& over this list you get a list of conditions symbol > 0, to which we just have to apply And in order to get the final condition.

The rest of the function definition is straightforward.

-

x=.;

F[x_?NonNegative] := x^(1/2)