TransWikia.com

NDSolve involves previous time step value

Mathematica Asked by VTeh on January 20, 2021

I am trying to use NDSolve to solve problems involve previous time step value. For example, instead of using the working code below:

    NDSolve[{x'[t] == a[t] Sin[t], x[0] == 0, a[0] == 1, 
           WhenEvent[Sin[t] == 0, a[t] -> -a[t]]}, x, {t, 0, 20} , 
          DiscreteVariables -> {a}, StartingStepSize -> 0.1, Method -> {"FixedStep", 
  Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4, 
    "Coefficients" -> ClassicalRK4Coefficients}}];

how i wish i could replace the WhenEvent above with

WhenEvent[x[t]-x[t-0.1] < 0, a[t] -> -a[t]]

(to note x[t] is current value and x[t-0.1] is previous value). I have no idea how to apply it, anyone can enlighten me?

One Answer

This question can be solved by storing the old value of x as an additional discrete variable.

s = Flatten@NDSolve[{x'[t] == a[t] Sin[t], x[0] == 0, a[0] == 1, tem[0] == 0, 
    WhenEvent[Mod[t, .1] == 0, {If[x[t] - tem[t] < 0, a[t] -> -a[t]], tem[t] -> x[t]}]}, 
    {x, a}, {t, 0, 20}, DiscreteVariables -> {a, tem}, StartingStepSize -> 0.1, 
  Method -> {"FixedStep", Method -> {"ExplicitRungeKutta", "DifferenceOrder" -> 4}}];

Plot[x[t] /. s, {t, 0, 20}, AxesLabel -> {t, x}]

enter image description here

Plot[a[t] /. s, {t, 0, 20}, AxesLabel -> {t, a}]

enter image description here

Note that this method works equally well for non-constant time-steps.

Correct answer by bbgodfrey on January 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP