Question

I'm trying to make a RecurrenceTable with conditionals in Mathematica, and the recursive stuff is working right, but it won't evaluate it completely.

In:= RecurrenceTable[{x[n] == If[Mod[n, 2] == 0, x[n - 1], y[n - 1]], 
       y[n] == If[Mod[n, 2] == 0, R x[n - 1] (1 - x[n - 1]), y[n - 1]], 
       x[1] == x0, y[1] == 0}, {x, y}, {n, 1, 10}]

Out:= {{0.25, 0.}, {x[1], 3 (1 - x[1]) x[1]}, {y[2], y[2]}, {x[3], 
        3 (1 - x[3]) x[3]}, {y[4], y[4]}, {x[5], 3 (1 - x[5]) x[5]}, {y[6], 
        y[6]}, {x[7], 3 (1 - x[7]) x[7]}, {y[8], y[8]}, {x[9], 
        3 (1 - x[9]) x[9]}}

These are the right results, but I need it to be in numeric form, i.e. {{0.25, 0.}, {0.25, 0.5625} ...

Is there a way to do this? Thanks!

Was it helpful?

Solution

Typically, you should use Piecewise for mathematical functions, and reserve If for programming flow.

You can convert many If statements using PiecewiseExpand:

If[Mod[n, 2] == 0, x[n - 1], y[n - 1]] // PiecewiseExpand
If[Mod[n, 2] == 0, r*x[n - 1] (1 - x[n - 1]), y[n - 1]] // PiecewiseExpand

The final code may look something like this:

r = 3;
x0 = 0.25;
RecurrenceTable[
 {x[n] == Piecewise[{{x[n - 1], Mod[n, 2] == 0}}, y[n - 1]],
  y[n] == Piecewise[{{r*x[n - 1] (1 - x[n - 1]), Mod[n, 2] == 0}}, y[n - 1]],
  x[1] == x0,
  y[1] == 0},
 {x, y},
 {n, 10}
]
{{0.25, 0.}, {0.25, 0.5625}, {0.5625, 0.5625}, {0.5625, 
  0.738281}, {0.738281, 0.738281}, {0.738281, 0.579666}, {0.579666, 
  0.579666}, {0.579666, 0.73096}, {0.73096, 0.73096}, {0.73096, 0.589973}}

A couple of related points:

  1. It is best not to use capital letters for your symbol names, as these may conflict with built-in functions.

  2. You may consider Divisible[n, 2] in place of Mod[n, 2] == 0 if you wish.

OTHER TIPS

RecurrenceTable[{
 x[n] == Boole[ Mod[n,2] == 0 ] x[n-1] +
         Boole[ Mod[n,2] != 0 ] y[n-1],
 y[n] == Boole[ Mod[n,2] == 0 ] 3 x[n-1] (1-x[n-1]) + 
         Boole[ Mod[n,2] != 0 ] y[n-1],
 x[1] == .25, y[1] == 0},
 {x, y}, {n, 1, 10}]

with edits R = 3 and x0 = .25 gives the output you expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top