3
$\begingroup$

This is essentially a follow-up to the question/answer here: How to define a differential operator?

Suppose I wish to define an operator DiffOp, e.g.,

DiffOp[t_]:=D[#,t]+4t D[#,{t,2}]&;

but in such a way that the function can read in the argument without having to state it explicitly. Can this be done? If so, how?

In code, what I'd like (using the example above) is a definition that would give

DiffOp[f[x]]

(* f'[x]+4x f''[x] *)

and

DiffOp[x^2+Sin[x]]

(* 10x+Cos[x]-4x Sin[x] *)

Note that I'm not explicitly calling the function as DiffOp[x][...].

Thanks!

Edit: I changed the example expression to be more complicated to test.

$\endgroup$

2 Answers 2

1
$\begingroup$

This works:

diffOp[a_] := Module[{sym},
  sym = DeleteDuplicates@Cases[a, _Symbol, Infinity];
  If[
   Length@sym == 1,
   Return[D[a, First@sym] + 4 First@sym D[a, {First@sym, 2}]]
   ]
  ]

then

diffOp[y^2 + Sin[y]]

2 y + Cos[y] + 4 y (2 - Sin[y])

$\endgroup$
1
$\begingroup$

Perhaps you can use the undocumented internal function Reduce`FreeVariables to determine the free variables:

DiffOp[expr_] := Replace[Reduce`FreeVariables[expr],
    {
    {} -> expr,
    {x_} :> D[expr, x],
    x_List :> D[expr, {x}]
    }
]

A couple examples:

DiffOp[x^2+Sin[x]]
DiffOp[x^2+Sin[Subscript[y, 1]]^2]

2 x + Cos[x]

{2 x, 2 Cos[Subscript[y, 1]] Sin[Subscript[y, 1]]}

The latter example shows that Reduce`FreeVariables thinks that subscripted variables can be free variables as well as just ordinary symbols.

$\endgroup$
1
  • $\begingroup$ What exactly does Reduce`FreeVariables do? I seem to be getting drastically different results for these two similar expressions: Reduce`FreeVariables[ f[g[d[rho]],g[d[s[rho, m, n]]]]*(-x[0,a^2,u,v,m]-2*a*x[1,a^2,u,v,m])] versus Reduce`FreeVariables[ f[g[d[rho]],g[d[s[rho, m, n]]]]*(-x[0,a^2,u,v,m]-2*x[1,a^2,u,v,m])]. $\endgroup$
    – QuantumDot
    Jan 1, 2020 at 21:15

Your Answer

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

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