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:= F[func_] := Block[{y}, y[x_] = func;
x y''[x] + 2 y'[x] + l^2 x y[x] == 0]

In:= F[Cos[x]]

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

and

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

In:= F[Cos[x]]

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

The methods in the link will work:

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

In:= F[Cos[x]]

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

or

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

In:= F[Cos[x]]

Out= -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.