Random number between 0 and 4

I am trying to generate a random number between 0 and 4 and also 0 and xxxx. I have tried a number of options, but a pattern always seems to occur. I have tried calling random from within a loop to generate different seed numbers.
My main problem seems to be that the results of random number generation favour certain numbers, ie 0 is rarely the result but 4 is returned as a result much more often.
Any help or ideas please? Thanks.


Technical Support
Staff member
The pseudo random number generation on a PICAXE is entirely predictable, based on shifting left and then setting the lsb, or not. The sequence will cycle through all possible 65,536 values, but using byte not word variables reduces the cycle to just a handful, so make sure you use a word variable to hold the random number.

Manipulating a word variable to produce a range of numbers, in this case likely to be -<code><pre><font size=2 face='Courier'> Random randomNumber
randomValueChosen = randomNumber // 5 ' Result is 0 to 4 </font></pre></code> can give a skewed outcome.

There are two simple options; keep track of the last random number chosen, and repeat getting a new random number until it is different ( which could also result in a repeating / alternating sequence ) or try other manipulations on the number such as -<code><pre><font size=2 face='Courier'> Random randomNumber
randomValueChosen = randomNumber / K // 5 ' Result is 0 to 4 </font></pre></code> where 'K' is some number which will have to be found by experimenting. You can always use both techniques.

Beyond that, it's a case of writing your own random number generator. If you have a loop whose length depends on how long a user delays, such as pushing a button, you can try -<code><pre><font size=2 face='Courier'> Do
randomNumberChosen = randomNumberChosen+1 // 5
Loop Until pin0 &lt;&gt; 0
Gosub UseTheRandomNumber </font></pre></code>


Senior Member
Also have a look at this: <A href='http://www.rev-ed.co.uk/picaxe/forum/Topic.asp?topic_id=7243&amp;forum_id=31&amp;Topic_Title=RANDOM%2Bmistake&amp;forum_title=PICAXE+Forum' Target=_Blank>External Web Link</a>