# WhenEvent and Piecewise inside NDSolve

A = Table[Sin[2 Pi/ x], {x, 1, 50}];

NDSolve[{y''[x] + Sin[y[x]] y[x] ==
Piecewise[{{Interpolation[A, kkk[x]], z[x] == 1}, {0, True}}],
y == 1, y' == 0, kkk == 100, z == 0,
WhenEvent[x > 9, {z[x] -> 1, kkk[x] -> 1}]}, y, {x, 0, 30},
DiscreteVariables -> {kkk, z}]


By using above code I get this error

InterpolatingFunction::dmval: "Input value {100.} lies outside the range of data in the interpolating function. Extrapolation will be used.

but when I change the WhenEvent as follow there is no error.

WhenEvent[x > 9, {kkk[x] -> 1, z[x] -> 1}]}


Could anybody explain the reason behind this? It is a simple example of what I am doing. I need to use Discrete Variables which change inside WhenEvent as a input of a function in NDSolve.

• At x=0, kkk[x]=100, however your Interpolation only knows the value of A for x (different x...) up to 50 ,as you define in your Table. Hence, it must extrapolate. May 12, 2016 at 23:23
• @Quantum_Oli At x==0, kkk is 100 but z is also 0 so the first condition inside Piecewise is not satisfied.
– Ali
May 12, 2016 at 23:35

This admittedly strange behavior does not occur at x == 0, as one might suppose, but at x == 9, as can be seen by using, for instance,

WhenEvent[x > 40, {z[x] -> 1, kkk[x] -> 1}]


for which no error message occurs. For the code as in the question, at x == 9, first z[x] -> 1 is executed, next Piecewise seems to be executed (because its argument has changed), creating an error message, and finally kkk[x] -> 1 is executed. In contrast,

WhenEvent[x > 9, {kkk[x] -> 1, z[x] -> 1}]


executes kkk[x] -> 1 first at x == 9, so no error occurs, consistent with the behavior described in the question. A somewhat similar situation is illustrated in the final example under "Possible Issues" in the WhenEvent documentation. A robust solution is to execute both simultaneously,

WhenEvent[x > 9, {z[x], kkk[x]} -> {1, 1}]


which works well.