Message Boards Message Boards


Replacing functions and variables

Posted 2 months ago
4 Replies
0 Total Likes

Say I have $f(x,y) + \partial_x f(x,y)$ e.g.

fun = f[x,y] + D[f[x,y],x]

I would like to use the substitution $f(x,y) \rightarrow \delta^2g(\delta x, \delta y)$ to get a new function. I have tried various things such as

fun /. {f[x, y] -> \[Delta]^2 g[\[Delta] x, \[Delta]y]}
fun /. {f -> \[Delta]^2 g}
fun /. {{f -> \[Delta]^2 g}, {x -> \[Delta] x}, {y -> \[Delta] y}}
fun /. {{f[x, y] -> \[Delta]^2 g[\[Delta] x, \[Delta]y]}, {D[f[x, y], 
 x] -> D[\[Delta]^2 g[\[Delta] x, \[Delta] y], x]}}

none of which produce the desired output of $\delta^2g(\delta x, \delta y) + \delta^3\partial_xg(\delta x, \delta y)$. The last(4th) attempt seems to be the closest, but the output is a two element list, with each element having a correct and incorrect term.

4 Replies

Use Function:

fun /. f -> Function[{x, y}, \[Delta]^2 g[\[Delta] x, \[Delta] y]]
Posted 2 months ago


Unless I missed something there should be d^2 next to the first term, or?

Here is what you can do:

fun /. f -> Function[{x, y}, d^2 g[ d x, d y]] 

or, less verbose

fun /. f -> ( d^2 g[ d #, d #2]& )

Why did your examples fail?

Nothing prevents D[f[x,y],x] from evaluation so it evaluates to Derivative[1, 0][f][x, y].

  • This is why your first example fails, it does not much it.
  • The second example does not work because you are replacing f, which is an operator with a product of \[Delta]^2 g where g was supposed to be an operator but how could MMA know it.
  • Same story with the third example, additionaly, if you have a list of list of replacements you will get a list. You should provide a flat list of rules to get one result only.

  • If you would've applied a flat list in the forth example, you'd get a correct result. But writing rules for each derivative is not something one would like to do. My solution avoids that because if you replace f in Derivative[...][f] with a function, Derivative will take care about applying the chain rule.

Posted 2 months ago

Thanks! Very helpful. Yes, there should be a d^2. I've edited it now.

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract