# Nesting multiple conditional functions

I am trying to implement a kind of random walk, where at each step there are three "coin tosses" (random numbers used to determine whether or not an event takes place. the three functions are:

f = If[RandomReal[] < LR, # + 1, #] &
g = If[RandomReal[] < OBR, # - 1, #] &
h = If[RandomReal[] < beta*#*(# - 1) && # > 1, # - 2, #] &


I can Nest any one of these functions to obtain a value for N after some number of steps Nest[f, 6, 5]. What I would like to do is nest all three, so that three random number are drwan at each time step, something like Nest[{f,g,h},6,5]

Can anyone help me to do this? I'd like to find a neat way that avoids loops if one exists.

Many thanks

• Both of the answers below are very helpful. I was perhaps not clear enough in the question. Rather than 3 random variables, I want each random operation to act on the same variable at each time step (ie to increment it by +/-1 or 2). I think I can see how to do this now from your code. Commented Feb 15, 2017 at 16:28
• Am I correct in interpreting this to mean: At each time step, first increment the given variable according to f, then g, then h? (Or some other order.) Does simply Nest[ h@*g@*f ,6,5] work? Commented Apr 15, 2017 at 5:44

Since you do not provide working code, I will make up a set of three functions the do work. I believe they are similar enough in form, if not in detail, for you adapt my code to your application.

walk3D[n_, start_] :=
Module[{p1, p2, p3},
p1 = .5; p2 = .3; p3 = .7;
NestList[
Through[
{If[#2[[1]] < p1, #1[[1]] + 1, #[[1]]] &,
If[#2[[2]] < p2, #1[[2]] + 1, #1[[2]]] &,
If[#2[[3]] < p3, #1[[3]] - 2, #1[[3]]] &}[#, RandomReal[1., 3]]] &,
start, n]]

SeedRandom[42]; walk3D[15, {0, 0, 0}]

{{0, 0, 0}, {1, 0, -2}, {2, 0, -4}, {3, -1, -6}, {3, -2, -8},
{3, -2, -8}, {3, -2, -10}, {4, -3, -12}, {4, -3, -12}, {4, -3, -14},
{4, -4, -14}, {5, -5, -14}, {5, -5, -14}, {6, -5, -16}, {6, -5, -16}}


I recommend using SetDelayed instead of Set to generate different values for RandomReal[] each time the code is executed.

namely:

f := If[RandomReal[] < LR, # + 1, #] & (* notice := instead of = *)
g := If[RandomReal[] < OBR, # - 1, #] &
h := If[RandomReal[] < beta*#*(# - 1) && # > 1, # - 2, #] &


walkRandom[n_] := With[{LR = .5, OBR = .3, beta = .7, seed = SeedRandom[42]},
f := If[RandomReal[] < LR, # + 1, #] &;
g := If[RandomReal[] < OBR, # - 1, #] &;
h := If[RandomReal[] < beta && # > 1, # - 2, #] &;

NestList[Function[x, MapThread[#1@#2 &, {{f, g, h}, x}]], {0, 0,0}, n] ]


walkRandom[15]

(* {{0, 0, 0}, {1, 0, 0}, {2, 0, 0}, {3, -1, 0}, {3, -2, 0}, {3, -2, 0},
{3, -2, 0}, {4, -3, 0}, {4, -3, 0}, {4, -3, 0}, {4, -4, 0}, {5, -5, 0},
{5, -5, 0}, {6, -5, 0}, {6, -5, 0}, {6, -6, 0}} *)


similarly you can replace the last line inside With with the one below

NestList[Function[x, {f@x[[1]], g@x[[2]], h@x[[3]]}], {0, 0, 0}, n]]