
Iterative Functions and the HP48, Part 2     Revised version

Continuing Part 1's introductory look at iterative functions with some
graphics programs for the HP48.

                                         (c) Bill Markwick, May/99
                                             bd628@torfree.net


In Part 1, we left John thinking about divorcing Linda because he wants
a German shepherd, but the shepherd won't come over from Germany without
his sheep, and Bob won't come out from under the bed because he's
convinced that the CIA is trying to put marmalade in his shoes. However,
we'll leave that for now to look at an iterative function graphically.


2.1 Verhulst's Logistics Function
---------------------------------

P.F. Verhulst was a 19th-century Belgian mathematician who came up with
a simple iterative function for looking at population growth. It's
called the "logistics" or "restricted growth" or "Verhulst" function.

        Xn+1 = uXn(1-Xn)  (properly, u is the Greek mu, or micro)

The u is the growth rate and n is the nth-generation. If 1 is the
maximum value the environment can support, and X scales the population,
1-Xn is a measure of stability: obviously if Xn reaches one, a population
crash is imminent. The function also discourages unrestricted growth;
nothing real-world can grow without restrictions such as dwindling
resources. Looking at the outputs of many iterations shows what's
happening to the general growth. It works well for populations under
simple conditions and with constant resources (such as fruit flies in a
lab, or fleas in a Lab).
  The Verhulst function is in many books on chaos, differential
equations, etc. You can find out such intriguing facts as this: if the
initial population is zero, it will remain zero. No kidding.

Its main appeal as a demonstrator is (a) despite its simplicity, it
shows surprisingly complicated behavior under dynamic conditions, and (b),
it's in all the books, so I could swipe ideas.

If you plot the function for u = 2.5, say, nothing remarkable shows up.
It's a typical parabola (downward, single-malt Scotch falls out).

        { '2.5*X*(1-X)' 'X' }

All the interesting stuff happens between x = 0 and 1, so if you've
plotted the above with the defaults, zoom in. The bisector shows that
the fixed points are at 0 and 0.6. If you change the value of u from
2.5, putting it between 1 and 4, all that seems to happen is that the
parabola changes height and the upper fixed point shifts a bit. For the
case 0 < u < 1, the curve never reaches the bisector, so there's only
one FP at (0,0) and the population is doomed to decline to zero. For 0,
there's no curve at all.

But this is like looking at one perfect sinewave coming out of an
amplifier: it gives no indication what the amp will sound like under
audio conditions.

        %%HP: T(3)A(R)F(.);
        \<< \-> X '2.5*X*(1-X)' \>>

Try transferring or keying in and running the above repeatedly for an
initial value of .1 (Part 1 gave a shortcut that makes the HP48 write
programs for you with DEF). You'll see the numbers jump quickly to
.599nnn and .600nnn and then it alternates between similar numbers for a
long time (39 keypresses) until it finally pops into .6, the fixed
point.

A variation: substitute u for the 2.5 and create a global variable
called u. That way you can observe the change in orbits by altering the
number stored in u; if you made it a local variable, you'd have to enter
it each time. Keep u between 0 and about 4 - see further down for a
discussion of the effect of u on the orbit.

The following graphics program eliminates all that keypressing by using
visuals, at the cost of resolution.


2.2 Dynamic Conditions
----------------------

None of the HP48's built-in plots seemed right for plotting iteratives.
All the plots wanted to feed an X value into the function and plot what
came out as Y, or similar. With an iterative function, we need to let it
calculate using its own output as the next input as it goes, and the
following is what I came up with. No doubt it's not the only way to do
it.

This is a no-frills program that draws only points. The 'u*X*(1-X)'
function is already inside.

  A Note on the Programs: there's no error-handling at all. Since
  they're in UserRPL, they won't cause any serious trouble, but if you
  interrupt them with ON, they'll likely leave debris on the stack.
    Also: execution times are approximate.


Program: DOTS   Plots iteratives of uX(1-X)  Execution time: 8 sec.

%%HP: T(3)A(R)F(.);
\<< \-> u               @ Get initial value u..
  \<< ERASE {           @ Set up the graphics screen.
(-3.25,-1.55)
(3.25,1.6) X 0
(0,0) FUNCTION Y }
'PPAR' STO { # 0h
# 0h } PVIEW -2 6.5     @ Start a loop from -2 to 6.5.
    FOR N \-> X 'u*X*   @ Solve the function for the initial value.
(1-X)' DUP N SWAP       @ Make a coordinate from the counter value N
R\->C PIXON .1          @ and the output of the function, but
    STEP DROP { }       @ leave a copy of the output on the stack. Add
PVIEW                   @ 0.1 to N, and do it all again.
  \>>                   @ Number of horizontal dots (iterations) is 85.
\>>                     @ Press ON to exit graphics screen.

  Stack:
  level 2: initial value X0, between 0 and 1
  level 1: value of u, 0 to 4


Start with the initial value .1 and u = 2.5. Oh look, it drew a dotty
straight line, with no axes or menu or anything. Exciting stuff. Exit
with ON, and press Picture. Now you can use the (x,y) key to confirm
that the line is at .6, the FP for these values. Try entering .6 for X0
and .6 for u, and watch a once-proud race of dots quickly decline and
nosedive into a line of zeros. (Since this program uses ordinary
plotting coordinates rather than pixels, zero is halfway up.)

Note that you're *not* looking at a plot of f(x), but f[85](x). You're
looking at the orbit (which way the iterates are going): each dot
represents one of the keypresses you did when you did the iterates
manually. For techies, it might help to think of it as an oscilloscope
display: the horizontal is swept linearly and the voltage amplitude is
the vertical. The program "sweeps" the horizontal linearly in steps of
0.1 (one pixel). With each step, the function takes in its previous
output and calculates; the amplitude of the result (or results) is
displayed on the vertical (and a copy is left on the stack for the next
calculation).

Try different values for the initial value and for u; keep u between 1
and 3 and you'll notice a bit of jiggling of various sizes before the
iterates settle into the fixed point value (which, incidentally, is 1 -
(1/u) for this function). Note that due to the restricted amplitude,
small variations may not show - a small 2-cycle may look like a straight
line.

Things begin to get really interesting when u goes past 3. Try X0 = .2
and u = 3.1. You'll see what appears to be two individual lines (two
functions for the price of one!). In fact, if you played join-the-dots,
you'd see that they're joined in a vertical zigzag. In terms of
population growth, the long-term effect is stability, but alternate
generations suffer from a fixed boom-or-bust cycle.

The fact that it's really one trace and not two doesn't matter - because
it's a display of a 2-cycle with each cycle appearing independent, chaos
theorists call this effect a "bifurcation", or fork.


2.3 I Wish I Could Shimmy Like My Bifurcate
-------------------------------------------

One of the tenets of chaos theory is that small changes in initial
conditions can cause profound changes in the output of a complex system.
An example that's been written many times in the popular press is that
the beating of a butterfly's wings in Tokyo can later make a Toronto
plumber suddenly order 23 pizzas, all of them with anchovies. Strange
stuff, this chaos.

Values of u between 3 and 4 form a special category of the Verhulst
function. They're teetering in and out of stability without getting
*too* wild. Here are some values you can plug in (from Lauwerier; see
the References at the end). The value of .2 for X0 makes a good starting
number each time.

        u       Result
       ---     --------
       3.0     transition to 2-cycle
       3.2     2-cycle
       3.5     4-cycle (upper and lower lines are 2-cycles)
       3.74    5-cycle
       3.83    3-cycle
       4.0     chaos

What might appear at first to be random dots is in fact a cyclical
pattern, at least below 4. Above 4, good luck. Should only 2 or 3 dots
appear, it's because the iterates have escaped to minus infinity.

Point of interest: when chaos occurs, it might be unpredictable, but
it's deterministic. Try running .2 and 4.05 over and over - you'll get
the same pattern each time. But change 4.05 to 4.05001 and you'll have a
completely different pattern.


2.4 Into Orbit: Animated Graphical Display
------------------------------------------

Here's a more ambitious program that could be considered animation as it
plots the Verhulst parabola, the bisector, and then the path of the
orbit. The orbit's initial value begins on the x-axis and heads
vertically for the function. It then goes horizontally to the bisector,
then vertically to the function again. It continues stairstep bouncing
like that, with each contact with the function or the bisector
representing an iterate.

If a fixed point exists and it's an attractor (derivative < 1), the
orbit will end there, often with much circling as u increases above 2
(spiralling sets in when the vertex of the parabola is above the
intersection point). In other cases, such as a repelling FP and an
n-cycle, the path goes around and around the corners of its cycle,
getting nowhere spectacularly (the fixed point tends to become repelling
when u > 3). For chaotic values (u > 4), all bets are off. If the line
of iterates starts up but then disappears, it's on its way to infinity.

For best results, keep X0 between 0 and 1 - outside this range the
iterates quickly escape to infinity.


Program: STAIRS   Plots, animates Verhulst expr.   Execution time: 25 sec.

%%HP: T(3)A(R)F(.);
\<< \-> u                 @ Get value of u.
  \<< ERASE { # 0d        @ Set up graphics screen for a view that
# 0d } PVIEW { 'u*X       @ accommodates most values of u.
*(1-X)' X } STEQ {        @ Store function and bisector expressions in EQ.
(-.587348,-.246276682859) @ Hview coordinates
(1.5673483,1.05680173714) @ Vview coordinates
{ X -1 1.5 } .1 { (0,0)   @ .1 sets plot resolution.
{ # 10d # 10d } }
FUNCTION Y } 'PPAR'       @ Store view parameters in PPAR.
STO DRAX DRAW DUP 0       @ Draw the function's parabola and then
R\->C SWAP 20 \-> I       @ the y = x bisector.
    \<< 1 I               @ I = number of iterations, default 20.
      FOR Y DUP \-> X     @ Start iterative loop to generate coords.
'u*X*(1-X)' DUP 3         @ User coordinates of the staircase will all be
ROLLD R\->C DUP 3         @ made from the function's iterates, which
ROLL DUP DUP R\->C        @ is what all the rolling and duping is about.
DUP 3 ROLL
      NEXT 2 DROPN
4 I * \->LIST REVLIST     @ Put coords in a list and reverse it -
EVAL 1 2 I *              @ otherwise the line-drawing runs backwards.
      FOR C LINE          @ Draw a line for each pair of coords.
      NEXT { }
PVIEW                     @ Pressing ON exits the graphics screen.
    \>>
  \>>
\>>

  Stack:
  level 2: initial value X0
  level 1: value of u

Try running the same values that were listed for the DOTS program. In
terms of dramatic behavior, the best results are with u between 2.5 and
4. Going much past 4 into the chaos region doesn't make the orbit
crazier - it just bolts for infinity.

Guidelines for choosing u:

        0 to 1:  Dull. Almost nothing happens because iterates decay.
        1 to 2:  Stable. The staircase heads right to the FP.
        2 to 3:  Interesting - iterates circle the FP for larger values;
                 the beginnings of bifurcation.
        3 to 4:  "Would fill a book." - H. Lauwerier.

Changing things: you might want more iterations. These are controlled by
the I in line 11 (20 -> I). Change the 20 to whatever you want - you'll
get twice as many lines in the staircase as the value of I. (The reason
for the local variable I is that other parameters also use it, so it
lets you change everything in one go.)

There's no zoom feature. The displayed image is a compromise to allow
most values of u to be displayed (the greater u is, the higher the
parabola - its height is u/4). The Hview and Vview are set by the pairs
of round brackets in the PPAR list. One way to get numbers for this is
to use Plot and Zoom to your liking (with some other function) and then
examine the new PPAR.

The plot resolution is set to .1 (just below the Vview brackets). It's
also a compromise between speed and resolution.


2.5 Using Other Expressions
---------------------------

STA2 is STAIRS with the ability to use any expression. The "u" variable
has been removed, so if your expression needs a constant, it should be
in the expression itself. Or, if you're trying a lot of different
constants, you could always put the expression and the constant on the
stack and use the required operator, which would be faster than editing.

The display is set for functions that return numbers around 0 to 1;
outside this range, you'll have to manually change the Hview and Vview
parameters.


Program: STA2   Animates user-expression iterates   Execution time: 25 sec.

%%HP: T(3)A(R)F(.);
\<< 'EXPR' STO             @ Store user function in EXPR.
ERASE { # 0d # 0d }        @ Start graphics screen.
PVIEW 'EXPR' RCL {
X } + STEQ {               @ Store function and X list in EQ.
(-.587348,-.246276682859)  @ Hview parameter
(1.5673483,1.05680173714)  @ Vview parameter
{ X -1 2 } .1 {
(0,0) { # 10d # 10d
} } FUNCTION Y }
'PPAR' STO DRAX            @ Store plot parameters in PPAR.
DRAW DUP 0 R\->C SWAP
20 \-> I                   @ Number of iterations (20) into I.
    \<<
      IFERR 1 I            @ Start iterative loop.
        FOR Y DUP \->
x
          \<< x 'X'        @ Store output in X as global variable.
STO EXPR EVAL              @ Evaluate the function for X.
          \>> DUP 3
ROLLD R\->C DUP 3
ROLL DUP DUP R\->C
DUP 3 ROLL
        NEXT 2
DROPN 4 I * \->LIST        @ Coords in list and reversed (or else
REVLIST EVAL 1 2 I         @ they're drawn backwards).
*
        FOR A LINE         @ Draw the staircase using coords.
        NEXT 'X'           @ Delete X variable.
PURGE { } PVIEW            @ Press ON to exit graphics screen.
      THEN 'X'             @ Delete X if program is aborted.
PURGE
      END
    \>>
  \>>

  Stack:
  level 2: initial value X0
  level 1: user algebraic or program (must be in X; set radians for trig
           functions)

  Note: program overwrites EQ, EXPR, and any variable called 'X'.

You could try the sine or cosine experiments mentioned at the beginning
of the article (set radian mode). In that case, it's useful to multiply
the sine or cosine by a constant to control its amplitude - I'll call it
"m" in the following (usage: 'm*SIN(X)').

If the sine wave is just below the bisector (try X0 = 1.5, '.8*SIN(X)'),
you'll see the staircase head into the crevice between them, burrowing
its way to zero and demonstrating what you've read in many texts on
radian measure: for small values, SIN(X) is approximately equal to X,
and the approximation gets better as you get closer to zero.

Note that if m > 1, the sine wave is now cut by the bisector and the
staircase may head off to the right. That's because a new fixed point
appears (solve m*SIN(X)-x = 0 and you'll get two roots if m > 1).

If you have any books on chaos theory, you'll probably find lots of
iterative equations you can try out, or just pull equations out of an
algebra book. Some of them work well, some are boring. You might have to
adjust the Hview and Vview parameters (or rewrite the program to allow
zooming). Change the number of iterations from 20 to whatever you want
in the line 20 \-> I.

STA2 will also accept programs as the function, with the same
restriction that applies to plots - the program must take in and return
one real number (and also, it must be in X). Best display results are
outputs between 0 and 1 (again, because of the lack of zooming).

Here's one you can try. It tests whether a number is in the Cantor set.
To make a long story short: you can make a Cantor set by drawing a line
one unit in length and then removing the inner third, keeping the
endpoints. Now you do the same for the two short lines you've created,
and you repeat this to infinity or until your bum goes to sleep,
whichever occurs first. All the points left are in the set, and because
they have (theoretically) no width, they're called "Cantor dust".
  We'll meet the Cantor set again briefly in Part 3's graphical display
of bifurcations.


Program: CANT   Tests for Cantor set using STA2   Execution time: 25 sec.

%%HP: T(3)A(R)F(.);
\<<                 @ Not a standalone program - for use with STA2
  CASE X .5 \<=     @ If X is less than or equal to .5,
    THEN '3*X'      @ evaluate 3*X.
    END X .5 >      @ If X is greater than .5,
    THEN '-3*X+3'   @ evaluate -3*X+3.
    END 0           @ Otherwise X=0.
  END
\>>

  Stack:
  level 2: X0 between 0 and 1
  level 1: the above CANT program

Now run STA2. You'll see a triangle, the bisector, and at least a few
lines of the iterations bouncing around. If the lines converge on a
point, the test number is in the set. If they escape out of the screen,
they're not in the set (the Cantor numbers are related to powers of 1/3,
such as 1/9, 7/9, etc.). O and 1 are the attractors; if you calculate
the FP for -3*X+3, it's .75 - but it's repelling. If X0 is .75, then
bang, right to the FP as described in Part 1. But try .749 and the lines
will go zinging all over the display trying to escape to minus infinity,
which they do eventually.


That's it for Part 2. In Part 3, some iterative graphical demonstrators
that are simple fractals.


Bill Markwick
Toronto, Ontario, Canada
bd628@torfree.net

