4
$\begingroup$

I am looking for the function equivalent of Sympy's function: as_independent (*deps, **hint) in Mathematica. The function naively separates an expression into arguments that are not dependent on deps. This operation does not work for non-commutative terms, since they cannot always be separated out.

For example, let us consider the expression

F[x_,t_,a_] = Cos[2*t] Sin[5 x] Exp[-2 t] t^3 a

We observe that $f(x,t,a) = T(t)*X(x)*A(a)$ and thus the equation is separable in its arguments $x,t,a$. Suppose I would like to separate the equation in its arguments x and t. For argument t, this operation should return $X(x)*A(a)$ and $T(t)$

  1. Sin[5x] a

  2. Cos[2*t] Exp[-2t] t^3

For argument x the operation should return $T(t)*A(a)$ and $X(x)$

  1. Cos[2*t] Exp[-2t] t^3 a

  2. Sin[5x]

Is this possible in Mathematica?

$\endgroup$
3
$\begingroup$

This assumes that you are giving a single term, whose Head is Times,

asIndependent[prod_, var_] := 
 Times @@@ 
  SortBy[GatherBy[List @@ prod, FreeQ[var] ], Not@*FreeQ[var]];

I wish there were an option to GatherBy that would make it sort by the same function, but so be it - I had to use SortBy as well so that the return order would be consistent.

asIndependent[Cos[2*t] Sin[5 x] Exp[-2 t] t^3 a, t]
asIndependent[Cos[2*t] Sin[5 x] Exp[-2 t] t^3 a, x]
asIndependent[Cos[2*t] Sin[5 x] Exp[-2 t] t^3 a, a]
(* {a Sin[5 x], E^(-2 t) t^3 Cos[2 t]} *)
(* {a E^(-2 t) t^3 Cos[2 t], Sin[5 x]} *)
(* {E^(-2 t) t^3 Cos[2 t] Sin[5 x], a} *)

Edit I wanted to make the function as close to the python function as possible, so I've adjusted it so it will work with any object whose Head is Plus or Times

asIndependent[expr_, var_] := If[MemberQ[{Plus, Times}, Head[expr]],
  Head[expr] @@@ 
   SortBy[GatherBy[List @@ expr, FreeQ[var]], Not@*FreeQ[var]]]

The results above are identical, and we can do the following test cases as well

asIndependent[x + x y, x]
asIndependent[x + x y, y]
asIndependent[2 x Sin[x] + y + x + z, x]
asIndependent[(x - n1) (x - y), x]
(* {x + x y} *)
(* {x, x y} *)
(* {y + z, x + 2 x Sin[x]} *)
(* {(-n1 + x) (x - y)} *)

The only thing I haven't done yet is to make it take multiple variables, like asIndependent[2 x Sin[x] + y + x + z,{x,y}] - it shouldn't be too hard but it will make it more complicated I think.

$\endgroup$

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.