How to do substitution of a function in mathematic

2020-06-15 03:03发布

问题:

I have the expression D[f[x, y], x], and I want to substitute f[x,y] with x*y, I tried the following:

D[f[x, y], x] /. {f[x,y] -> x*y} and D[f[x, y], x] /. {f -> x*y}

But neither worked. Would appreciate your help! Thanks.

回答1:

The FullForm of the derivative in your expression is

In[145]:= D[f[x,y],x]//FullForm

Out[145]//FullForm= Derivative[1,0][f][x,y]

This should explain why the first rule failed - there is no f[x,y] in your expression any more. The second rule failed because Derivative considers f to be a function, while you substitute it by an expression. What you can do is:

In[146]:= D[f[x,y],x]/.f->(#1*#2&)

Out[146]= y

Note that the parentheses around a pure function are essential, to avoid precedence - related bugs.

Alternatively, you could define your r.h.s through patterns:

In[148]:= 
fn[x_,y_]:=x*y;
D[f[x,y],x]/.f->fn

Out[149]= y

HTH



回答2:

Nothing new, just the way I usually think of it:

D[f[x, y], x] /. f -> Function[{x, y}, x y]

Out

y


回答3:

You can also try Hold and Release or Defer etc.

Hold@D[f[x, y], x] /. {f[x, y] -> x*y}

D[x y, x]    


Hold@D[f[x, y], x] /. {f[x, y] -> x*y} // Release

y