0
$\begingroup$

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[434]:= If[RandomReal[] > 0.5, Print["banana"], Print["apple"]] // AbsoluteTiming

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



Out[434]= {0.000139843, Null}

Out[435]= {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[452]:= list = Range[10]
list2 = Range[10]

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

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

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

Out[454]= {0.0000419101, x}

Out[455]= {0.0000367782, x}

Out[456]= {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[[5]]=x,0}],0}]//AbsoluteTiming

Tally[Table[RandomChoice[{r,1-r}->{RandomChoice[{p,1-p}->{list[[5]]=x,0}],0}],100]]
Out[476]= {0.0000774053,x}
Out[477]= {{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?

$\endgroup$
  • $\begingroup$ 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[[5]] = x]]. $\endgroup$ – J. M. will be back soon Mar 29 '18 at 11:54
  • $\begingroup$ @J. M. Nice! little faster as well, thanks $\endgroup$ – Awkward Panda Mar 29 '18 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.