# How to carry out a different function based on weighted probabilities

I am looking to carry out a function based on weighted probabilities

I have looked at using If[] and random numbers but RandomChoice[] seems much faster

In:= If[RandomReal[] > 0.5, Print["banana"], Print["apple"]] // AbsoluteTiming

RandomChoice[{0.5, 0.5} -> {"banana", "apple"}] // AbsoluteTiming

Out= {0.000139843, Null}

Out= {0.000020955, "banana"}


I want to create a function that will carry out a list manipulation given a certain probability, will a function inside RandomChoice[] work?

The timing changes, is Print[] a slow function?

In:= list = Range
list2 = Range

Out= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Out= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

In:= If[RandomReal[] > 0.5, list2[] = x, Print["apple"]] // AbsoluteTiming
RandomChoice[{0.5, 0.5} -> {list[] = x, "apple"}] // AbsoluteTiming
list

Out= {0.0000419101, x}

Out= {0.0000367782, x}

Out= {1, 2, 3, 4, x, 6, 7, 8, 9, 10}


My end goal is to create a simple model of a chemical interaction. If a chemical attaches with probability r is rejected (1-r) once attached it 'reacts' with probability p or rejects with (1-p)

Can I put a RandomChoice within a RandomChoice ? Or is there a better way?

(I'm trying to avoid implementing a more complicated 'reaction' with algorithms such as Gillespie or Michaelis-Menten- or would they be quicker? especially within matrix operations?)

My attempt:

r=0.5;
RandomChoice[{r,1-r}->{RandomChoice[{p,1-p}->{list[]=x,0}],0}]//AbsoluteTiming

Tally[Table[RandomChoice[{r,1-r}->{RandomChoice[{p,1-p}->{list[]=x,0}],0}],100]]
Out= {0.0000774053,x}
Out= {{0,52},{x,48}}


*Edit Ideally I would like to do the function or 'nothing', is there a way to make x in the example do nothing?

• I would have done your last example as If[RandomChoice[{r, 1 - r} -> {1, 0}] > 0, If[RandomChoice[{p, 1 - p} -> {1, 0}] > 0, list[] = x]]. – J. M.'s technical difficulties Mar 29 '18 at 11:54
• @J. M. Nice! little faster as well, thanks – Awkward Panda Mar 29 '18 at 12:11