I have noticed that there are a few examples that go into some detail regarding While loop alternatives. (See here for example: Alternatives to While Loops?) However, I wanted to provide a simpler example for clarity, and to help affirm something which I am currently unclear about.
Can someone give a simple, faster alternative to the following code containing a While loop? (It counts the number of iterations taken before a pseudorandom uniform number on [0,1] to be generated.)
Module[{cSwitch, cCount, cRand}, cSwitch = 0; cCount = 0; cRand = 0.9999;
While[cSwitch == 0, aRand = RandomReal[]; cCount += 1;
If[aRand > cRand, cSwitch = 1]]; cCount] // Timing
A corollary question is, when should one use a While loop for simplicity, and when is it really beneficial to use an alternative? I am highlighting really just to emphasise that there is a tradeoff between readability of code and speed.
Best,
Ben
Block[{$IterationLimit = Infinity}, If[RandomReal[] > 0.9999, #, #0[# + 1]] &[0]]
. Another:NestWhile[# + 1 &, 0, RandomReal[] < 0.9999 &]
. $\endgroup$