Search code examples
juliaode

2nd Order ODEs in Julia using DifferentialEquations


I'm trying to solve the harmonic oscillator using DifferentialEquations in Julia. i.e.:

using DifferentialEquations
using Plots

m = 1.0                          
ω = 1.0                     

function mass_system!(ddu,du,u,p,t)
    # a(t) = (1/m) w^2 x 
    ddu[1] = (1/m)*(ω^2)*u[1]
end

v0 = 0.0                     
u0 = 1.0                  
tspan = (0.0,10.0)               

prob = SecondOrderODEProblem{isinplace}(mass_system!,v0,u0,tspan,callback=CallbackSet())
sol = solve(prob)

But it doesn't seem to understand the ODE constructor. Upon running, I get:

ERROR: LoadError: TypeError: non-boolean (typeof(isinplace)) used in boolean context
Stacktrace:
 [1] #_#219(::Base.Iterators.Pairs{Symbol,CallbackSet{Tuple{},Tuple{}},Tuple{Symbol},NamedTuple{(:callback,),Tuple{CallbackSet{Tuple{},Tuple{}}}}}, ::Type{SecondOrderODEProblem{DiffEqBas
e.isinplace}}, ::Function, ::Float64, ::Float64, ::Tuple{Float64,Float64}, ::DiffEqBase.NullParameters) at /Users/brandonmanley/.julia/packages/DiffEqBase/avuk1/src/problems/ode_problems
.jl:144
 [2] Type at ./none:0 [inlined] (repeats 2 times)
 [3] top-level scope at /Users/brandonmanley/Desktop/nBody/nBodyNN/test.jl:25
 [4] include at ./boot.jl:328 [inlined]
 [5] include_relative(::Module, ::String) at ./loading.jl:1105
 [6] include(::Module, ::String) at ./Base.jl:31
 [7] exec_options(::Base.JLOptions) at ./client.jl:287
 [8] _start() at ./client.jl:460

Any ideas?


Solution

  • I would highly recommend looking at some of the tutorials. You have a few mistakes here which are addressed in this tutorial on classical physics models. Specifically, you shouldn't use an in-place modifying function if you choose a state variable that cannot be mutated, i.e. a scalar. If that's the case, just use the out-of-place form where you generate the output. That looks like:

    using DifferentialEquations
    using Plots
    
    m = 1.0                          
    ω = 1.0                     
    
    function mass_system!(du,u,p,t)
        # a(t) = (1/m) w^2 x 
        (1/m)*(ω^2)*u[1]
    end
    
    v0 = 0.0                     
    u0 = 1.0                  
    tspan = (0.0,10.0)               
    
    prob = SecondOrderODEProblem(mass_system!,v0,u0,tspan)
    sol = solve(prob)