3

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.

loup-garou
  • 65
  • 5

3 Answers3

5

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}

Mathematica graphics

Nasser
  • 143,286
  • 11
  • 154
  • 359
  • Thanks for this trick! But I should have said my intent was more to learn about pattern matching in Mathematica. – loup-garou Aug 27 '17 at 04:41
4

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
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
0

I figured out a much simpler solution,

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