2
$\begingroup$

The code below works fine.

 DN[n_Integer] := n; n = 0;
 NDSolve[{x'[t] == Cos[t] + a[t], x[0] == a[0] == 0, WhenEvent[Mod[t, 1] == 0, {a[t] -> a[t] + DN[n], n = n + 1}]}, x[t], {t, 0, 30}, DiscreteVariables -> {a[t], n, DN}]

But it does not work if I try to replace NDSolve with DSolve , and the warning says "Equation or list of equations expected instead of WhenEvent..." How shall I correct the code if I wish to insist on DSolve.

$\endgroup$

1 Answer 1

3
$\begingroup$

In Mathematica v12.2(Thanks @cvgmt's comment ) WhenEvent only works for numerical solvers like NDSolve,..., not with DSolve. In newer versions DSolveis allowed.

I'm wondering why your example works!

DN[] is an external function, shouldn't be redefined in DiscreteVariables. Same with n.

Try

DN[n_ ] := n; 
sol = NDSolveValue[{x'[t] == Cos[t] + a[t], x[0] == a[0] == n[0] == 0, 
WhenEvent[Mod[t, 1] == 0, {a[t] -> a[t] + DN[n[t]], n[t] -> n[t] + 1}]}, 
{x,a,n} , {t, 0, 30}, DiscreteVariables -> {a , n }];
Plot[ Through[sol[t]], {t, 0, 30}]

enter image description here

$\endgroup$
6
  • $\begingroup$ According to the document, WhenEvent expressions can be used in NDSolve, NDSolveValue, ParametricNDSolve, ParametricNDSolveValue, DSolve, and DSolveValue. For example, DSolve[{y''[t] == -9.81, y[0] == 5, y'[0] == 0, WhenEvent[y[t] == 0, y'[t] -> -0.95 y'[t]]}, y, {t, 0, 10}] $\endgroup$
    – cvgmt
    Nov 29, 2023 at 9:22
  • $\begingroup$ @cvgmt Thanks, my fault. My Mathematica version is v12.2 and here WhenEvent only defined for NDSoleve&Co $\endgroup$ Nov 29, 2023 at 9:29
  • $\begingroup$ +1, Your code work when we replace NDSolveValue to DSolveValue in v12.3 and v13.3.1. $\endgroup$
    – cvgmt
    Nov 29, 2023 at 9:30
  • $\begingroup$ @Ulrich Neumann Thanks a lot. Now the only question is why my original code works fine in NDSlove while not in DSolve. It seems WhenEvent works in a different way in DSolve than in NDSolve. $\endgroup$
    – metroidman
    Nov 29, 2023 at 10:50
  • 1
    $\begingroup$ @metroidman I think I can explain why NDSolve is fooled by DiscreteVariables -> {a[t], n, DN}. According to the Details section of document of DiscreteVariables: {v, vmin, vmax} means v has range vmin<=v<=vmax. So, {a[t], n, DN} just happens to be something meaning n<=a[t]<=DN. (In principle the non-numeric DN should still trigger a warning, I think this is arguably a bug. ) Actually if one writes e.g. DiscreteVariables -> {n, a[t], DN}, NDSolve will spit out a warning and fail. $\endgroup$
    – xzczd
    Nov 30, 2023 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.