1
$\begingroup$

RecurrenceTable is like NDSolve for difference equations, but lacks a lot of its bells and whistles. One thing I'd like to use in RecurrenceTable is WhenEvent. Is there an easy way to achieve this?

For example, something like

RecurrenceTable[{x[t + 1] == 3 x[t] (1 - x[t]), x[0] == 0.1, 
WhenEvent[x[t] > x[t - 1] && x[t + 1] > x[t], Print["max"]]}, x, {t, 0, 10}]

would detect local maxima, but this is just one potential application among many.

$\endgroup$
3
  • 2
    $\begingroup$ For the specific example, use FindPeaks on the output of RecurrenceTable $\endgroup$
    – Bob Hanlon
    Oct 8 '17 at 21:08
  • 2
    $\begingroup$ One way might be to write a function that looks like it does WhenEvent, from the outside, but actually just computes the recurrence table and then operates on the output with something like If[#2 > #1 && #2 > #3, Print[#2]] & @@@ Partition[rt, 3, 1];. It might get the convenience, but wouldn't actually be doing anything like the same thing (so StopIntegration wouldn't happen, although you could just return the output truncated to make it look like it stopped). $\endgroup$ Oct 8 '17 at 22:09
  • $\begingroup$ Good thoughts on that example. Any ideas on how to achieve “StopIntegration” or how to change DiscreteVariables? $\endgroup$
    – Chris K
    Oct 9 '17 at 1:02
3
$\begingroup$

You could use Nest/NestList and identify yourself, e.g.:

r[n_, fu_] := fu[3 # (1 - #) &, 0.1, n]
pos[n_] := 
 Flatten[Position[
   Partition[Sign@Differences[r[n, NestList]], 2, 1], {1, -1}]]
Show[ListPlot[r[10, NestList], Joined -> True, DataRange -> {0, 10}], 
 ListPlot[Callout[{#, r[#, Nest]}, Row[{"x[", #, "]=", r[#, Nest]}], 
     Above] & /@ pos[10], PlotStyle -> Red], PlotRange -> {0, 1}, 
 BaseStyle -> 12]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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