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?
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}]
Plot[a[t] /. s, {t, 0, 20}, AxesLabel -> {t, a}]
Note that this method works equally well for non-constant time-steps.
Correct answer by bbgodfrey on January 20, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP