# Rule that converts the order of a derivative to a power

I'm attempting to implement the variation of parameters method of solving a linear nonhomogeneous ODE (as a coding problem to help learn Mathematica). As a first step, I would like to form the characteristic equation of my ODE function.

My test ODE is:

f[x_, y_] := y'' + 3 y' - 2 y - Sin[E^-x]


Which has the characteristic equation:

s^2 + 3s - 2 = 0


My naive attempt at getting the characteristic equation is:

variationOfParameters[fun_] :=
Plus @@ Cases[fun[x, y], _.*y | _.*_Derivative[y]] /. {yPrime :_Derivative[y] ->
s^Extract[FullForm[yPrime],
Position[FullForm[yPrime], _Integer]], y -> 1}


The Cases part works, the ReplaceAll however does not (output is an empty list). But when I test the rule manually it produces the correct answer, e.g.

Extract[FullForm[y''],
Position[FullForm[y''], _Integer]]
(*{2}*)


What am I doing wrong? Additionally if you have any advice on making this function better, I would be happy to hear it.

Thank you.

I think this does what you want:

Select[f[x, y], Not@*FreeQ[y]] /. Derivative[n_][y] :> s^n /. y -> 1

-2 + 3 s + s^2


More obfuscated, but fun to write:

Tr @ Cases[f[x, y], x_. (Derivative[n_][y] | y) :> Last[x s^{0, n}]]

-2 + 3 s + s^2

• Wow this is beautiful and clean, thanks! Commented Aug 27, 2017 at 5:57
• @user3547456 You're welcome; I'm glad you like it. Commented Aug 27, 2017 at 6:04

I would like to form the characteristic equation of my ODE function.

to get the characteristic equation, which applies only to the homogeneous part of the ode, you can use the following LaplaceTransform trick

ClearAll[y,t,s];
odeH=y''[t]+3 y'[t]-2 y[t]==0;
lap=LaplaceTransform[odeH,t,s];
charEq= lap/.{LaplaceTransform[y[t],t,s]->1,y[0]->0,y'[0]->0}


• Thanks for this trick! But I should have said my intent was more to learn about pattern matching in Mathematica. Commented Aug 27, 2017 at 4:41

I figured out a much simpler solution,

variationOfParameters[fun_] :=
Plus @@ Cases[
f[x, y], _.*y | _.*_Derivative[y]] /. {Derivative[orders_][y] ->
s^orders, y -> 1}