# Discrete number does not work well in DSolve

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.

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}]


• 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}] Nov 29, 2023 at 9:22
• @cvgmt Thanks, my fault. My Mathematica version is v12.2 and here WhenEvent only defined for NDSoleve&Co Nov 29, 2023 at 9:29
• +1, Your code work when we replace NDSolveValue to DSolveValue in v12.3 and v13.3.1. Nov 29, 2023 at 9:30
• @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. Nov 29, 2023 at 10:50
• @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. Nov 30, 2023 at 9:12