# Substituting inside a differential equation

x y''[x]+2y'[x]+l^2 x y[x]==0/.y[x]->Cos[x]


I think above code shows what I want to do quite clearly. How do I make it happen. Only y[x] is replaced.

• Try y -> Cos. – J. M. will be back soon Jun 6 '15 at 8:32
• For more general usage you can use dChange like: dChange[ x y''[x] + 2 y'[x] + l^2 x y[x] == 0, y[x] == Cos[x] ]. 80241 - feedback appreciated. – Kuba Jun 6 '15 at 8:34
• @Guesswhoitis. what if I wanted to change it into Cos^2 ? – grdgfgr Jun 6 '15 at 8:36
• Then you do y -> Function[x, Cos[x]^2] – J. M. will be back soon Jun 6 '15 at 8:39
• thanks, make that into an answer so that the question doesnt remain unanswered – grdgfgr Jun 6 '15 at 8:42

This question has been asked for times, Evaluation of Derivative in a Module and Replace rule with function? Derivatives don't evaluate.

Here are several ways to solve it:

If you do not mind pollute Global namespace, assign the function first.

y[x_] = Cos[x]
x y''[x] + 2 y'[x] + l^2 x y[x] == 0


If you mind, assign it in a Block

Block[{y}, y[x_] = Cos[x];
x y''[x] + 2 y'[x] + l^2 x y[x] == 0]


or, replace it by a pure function:

x y''[x] + 2 y'[x] + l^2 x y[x] == 0 /. y -> Function[x, Cos[x]]


If you are trying to do something more complex, then these methods will fail:

In[1]:= F[func_] := Block[{y}, y[x_] = func;
x y''[x] + 2 y'[x] + l^2 x y[x] == 0]

In[2]:= F[Cos[x]]

Out[2]= l^2 x Cos[x] == 0


and

In[1]:= F[func_] := x y''[x] + 2 y'[x] + l^2 x y[x] == 0 /. y -> Function[x, func]

In[2]:= F[Cos[x]]

Out[2]= l^2 x Cos[x] == 0


The methods in the link will work:

In[7]:= F[func_] :=
Block[{y, e}, e = x y''[x] + 2 y'[x] + l^2 x y[x] == 0;
e /. y -> Function[x, #]] &[func]

In[8]:= F[Cos[x]]

Out[8]= -x Cos[x] + l^2 x Cos[x] - 2 Sin[x] == 0


or

In[11]:= F[func_] :=
x y''[x] + 2 y'[x] + l^2 x y[x] == 0 /. y -> Function[x, #] &[func]

In[12]:= F[Cos[x]]

Out[12]= -x Cos[x] + l^2 x Cos[x] - 2 Sin[x] == 0


I do not quite understand why the last two methods work, I hope someone can explain it in this answer.