Lopehert
Lopehert

Reputation: 17

Sympy not solving a ODE correctly?

I want to solve the ode f´´(x) + k*f(x) = 0. which is a trivial ODE to solve (https://www.wolframalpha.com/input?i=f%60%60%28x%29+%2B+kf%28x%29%3D0)

my code is

from sympy import * 
x,t,k,L,C1,C2 = symbols("x,t,k,L,C1,C2")
f=symbols('f', cls=Function)
g=symbols('g', cls=Function)

Fx = f(x).diff(x)
Fxx = f(x).diff(x,x)
Gtt = g(t).diff(t,t)
Gt = g(t).diff(t)


BC1 = 0
BC2 = L


Eq1_k_positive = dsolve(Eq1.subs(k,-k))
display(Eq1_k_positive)

Not really sure why I don't get the solution that I should get. and no its not the same when I use BCs that would get me a result I get 0 since I don't get the sin cos equation. any tips on what's not correct?

Upvotes: -1

Views: 113

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

This is your differential equation:

In [18]: k, x = symbols('k, x')

In [19]: f = Function('f')

In [20]: eq = Eq(f(x).diff(x, 2) + k*f(x), 0)

In [21]: eq
Out[21]: 
           2          
          d           
k⋅f(x) + ───(f(x)) = 0
           2          
         dx  

This is the solution returned by SymPy:

In [22]: dsolve(eq)
Out[22]: 
                ____           ____
           -x⋅╲╱ -k        x⋅╲╱ -k 
f(x) = C₁⋅ℯ          + C₂⋅ℯ   

That solution is correct for any nonzero complex number k.

There can be many equivalent forms to represent the general solution of an ODE. SymPy will choose a different form here if you specify something about the symbol k such as that it is positive:

In [24]: k = symbols('k', positive=True)

In [25]: eq = Eq(f(x).diff(x, 2) + k*f(x), 0)

In [26]: eq
Out[26]: 
           2          
          d           
k⋅f(x) + ───(f(x)) = 0
           2          
         dx           

In [27]: dsolve(eq)
Out[27]: f(x) = C₁⋅sin(√k⋅x) + C₂⋅cos(√k⋅x)

This solution is also correct for any nonzero complex number k but will only be returned if k is declared positive because it is only for positive k that there is any reason to prefer the sin/cos form to the exp form.

Upvotes: 1

Related Questions