# Problem with DSolve, NDSolve with WhenEvent, Boundary Value Problem

I got the same problem as in question: DSolve, NDSolve with WhenEvent Give Incorrect Solution for Simple ODE. The boundary conditions are not fulfilled in the solution using the WhenEvent.

Can this problem be solved somehow?

Clear["Global*"]
z = 0.1;
T = 4*2*π;
m = 4;
sol = DSolveValue[{x''[t] == -1/(4*m^2)* x[t] - 2*z/m*x'[t] +
1/m^2*Cos[t], x[0] == x[T], x'[0] == x'[T],
WhenEvent[x[t] == 0, x'[t] -> -x'[t]]},
x[t], {t, 0, T},
Method -> {"Shooting",
"StartingInitialConditions" -> {x[0] == 2, x'[0] == -0.60}}];
Plot[sol, {t, 0, T}]

• The problem is formulated incorrectly. For the second-order equation, 4 boundary conditions are set. If this is physics, then for the equation of motion one can pose the Cauchy problem, but not a boundary problem. Commented Feb 5, 2020 at 22:55

Try

z = 0.1;
T = 4*2*\[Pi];
m = 4;
sol = NDSolveValue[{x''[t] == -1/(4*m^2)*x[t] - 2*z/m*x'[t] +1/m^2*Cos[t], x[0] ==x[T], x'[0] == x'[T],WhenEvent[x[t] == 0, x'[t] -> -x'[t]]}, x, {t, 0, T},Method -> {"Shooting","StartingInitialConditions" -> {x[0] == 2, x'[0] == -0.60}}]
Plot[sol[t], {t, 0, T}, Evaluated -> True]


But the periodic boundary conditions are not fullfilled very well (no idea why)!!!

workaround Create your own shooting method with ParametricNDSolveValue, intial conditions x0,v0 and NMinimize:

X = ParametricNDSolveValue[{x''[t] == -1/(4*m^2)*x[t] - 2*z/m*x'[t] + 1/m^2*Cos[t], x[0] == x0,x'[0] == v0
, WhenEvent[x[t] == 0, x'[t] -> -x'[t]]}, x, {t, 0, T}, {x0, v0}]
shoot = NMinimize[{1, {X[x0, v0][T] == X[x0, v0][0],X[x0, v0]'[T] == X[x0, v0]'[0]}}, {x0, v0}]
(*{1., {x0 -> -1.09609, v0 -> 0.0968271}}*)


Check result

Plot[X[x0, v0][t] /. shoot[[2]], {t, 0, T}, Evaluated -> True]


• Thank you for your comment, but it still does not work correctly. x(0) is not equal to x(T). Commented Feb 5, 2020 at 16:54
• @János The problem seems to be the ShootingMethod` , I added a workaraound in my answer! Hope it helps. Commented Feb 6, 2020 at 8:09
• Thank you! It helped a lot! Commented Mar 27, 2020 at 10:29