# Extraneous reaped data with NDSolve and WhenEvent

Bug introduced in 9.0 or earlier and fixed in 10.1

In exploring What is the range of values $x$ for which $f(x)$ is higher than $k$ over a given domain?, I came across the following strange behavior:

With[{a = 0, b = 2, k = 0.1, f = Sin[10 #] &},
Last@Reap[
NDSolve[{ifun[t] == f[t],
in[a] == Boole[f[a] > k], x1[a] == a,
s'[t] == 1, s[a] == a,
WhenEvent[f[t] > k, {in[t] -> 1, x1[t] -> t}],
WhenEvent[f[t] < k, If[in[t] == 1, Sow[{x1[t], t}]]; {in[t] -> 0}]},
{}, {t, a, b}, DiscreteVariables -> {in, x1}]]
]
(*  {{{0.0100167, 0.304143}, {0.638335, 0.932461}, 6.76508*10^-8, {1.26665, 1.56078}}}  *)


Where does the 6.76508*10^-8 come from? Only pairs are sown. The output should be the same as the following:

Partition[x /. NSolve[Sin[10 x] == 1/10 && 0 < x < 2, x], 2]
(*  {{0.0100167, 0.304143}, {0.638335, 0.932461}, {1.26665, 1.56078}}  *)


(V10.0.2, Mac OSX 10.10.1)

• Mma v9 output {{{0.0100167, 0.304143}, 1.27866*10^-8, 1.27866*10^-8, 4.12524*10^-8, {0.638335, 0.932461}, {1.26665, 1.56078}, 9.32835*10^-8}} – Dr. belisarius Jan 22 '15 at 4:31
• If you use a Sow[expr, tag] the extra reaps aren't shown,so there are probably spurious Sows in the NDSolve[] code – Dr. belisarius Jan 22 '15 at 4:41
• Note that if you use If[in[t] == 1, {x1[t], t}] (without the Sow) and leave in the Reap you also reap something. As @belisarius mentions this is a spurious Sow with out a tag in NDSolve. Kernel code can not use Sow without a tag for exactly this reason. I'll file a bug and someone has to dig through it.... – user21 Jan 22 '15 at 8:48
• @user21 Thanks. I did report it last night ([CASE:2325293]). – Michael E2 Jan 22 '15 at 11:49
• FYI, I do not see this extra value in 10.0.2 or in the new 10.1 (all on windows) !Mathematica graphics this looks like OSX only issue – Nasser Apr 2 '15 at 7:54

## 1 Answer

As indicated in the comments, this bug has been fixed as of version 10.1.

With[{a = 0, b = 2, k = 0.1, f = Sin[10 #] &},
Last@Reap[NDSolve[{ifun[t] == f[t], in[a] == Boole[f[a] > k], x1[a] == a,
s'[t] == 1, s[a] == a, WhenEvent[f[t] > k, {in[t] -> 1, x1[t] -> t}],
WhenEvent[f[t] < k, If[in[t] == 1, Sow[{x1[t], t}]]; {in[t] -> 0}]}, {}, {t, a, b},
DiscreteVariables -> {in, x1}]]]

(* {{{0.0100167, 0.304143}, {0.638335, 0.932461}, {1.26665, 1.56078}}} *)

{Partition[x /. NSolve[Sin[10 x] == 1/10 && 0 < x < 2, x], 2]}

(* {{{0.0100167, 0.304143}, {0.638335, 0.932461}, {1.26665, 1.56078}}} *)