2

I am trying to compute a sequence of functions using iteration and keep running into problems trying to use built in looping commands because of the recursive nature of the definition. The code below (version 8) shows the first two functions y1 and y2. The output functions are also piecewise linear. Is there an easier way to compute yn for any $n$?

{a1, b1} = {.3, .6}; {a2, b2} = {.6, .3};

y0[x_] := x;

f1[x_] := b1*y0[x/a1];

g1[x_] := (b2 - b1)*y0[(x - a1)/(a2 - a1)] + b1;

h1[x_] := (1 - b2)*y0[(x - a2)/(1 - a2)] + b2;

y1[x_] := If[0 <= x < a1, f1[x], If[a1 <= x < a2, g1[x], h1[x]]];

Plot[y1[x], {x, 0, 1}]

f2[x_] := b1*y1[x/a1];

g2[x_] := (b2 - b1)*y1[(x - a1)/(a2 - a1)] + b1;

h2[x_] := (1 - b2)*y1[(x - a2)/(1 - a2)] + b2;

y2[x_] := If[0 <= x < a1, f2[x], If[a1 <= x < a2, g2[x], h2[x]]];

Plot[y2[x], {x, 0, 1}]
Svend Tveskæg
  • 425
  • 5
  • 14
Jon
  • 33
  • 3

1 Answers1

4

You don't need to loop, you can just do the recursion directly:

Clear[y, f, g, h];
y[0, x_] := x;
y[n_, x_] /; 0 <= x < a1 := f[n, x];
y[n_, x_] /; a1 <= x <= a2 := g[n, x];
y[n_, x_] := h[n, x];
f[n_, x_] := b1 y[n - 1, x/a1];
g[n_, x_] := (b2 - b1) y[n - 1, (x - a1)/(a2 - a1)] + b1;
h[n_, x_] := (1 - b2) y[n - 1, (x - a2)/(1 - a2)] + b2;

The main trick is to pass in n as one of the parameters to the functions. When you are doing recursion, always remember the termination condition! I've split the y function into several definitions with different conditions (/;). You could keep it as one big If statement if that's more comfortable.

Plot[y[7, x], {x, 0, 1}]

y7

wxffles
  • 14,246
  • 1
  • 43
  • 75