Shop OBEX P1 Docs P2 Docs Learn Events
Random Numbers on BS2/PBASIC 2.5 — Parallax Forums

Random Numbers on BS2/PBASIC 2.5

cmeyercmeyer Posts: 5
edited 2009-04-15 12:51 in Learn with BlocklyProp
HELP!

I have been cruising the net and keep finding other code for older versions....

I want to recreate a die roll 1-6, randomly. Shouldn't this be easy?

Every time I try to code it with the following, I continue to get the same results (not quite random). The following was designed to roll 100 dice and find the distribution between 1-6:
________________________________________________________________________________
' {$STAMP BS2}
' {$PBASIC 2.5}

a var word
c var byte
d var byte
f var byte
g var byte
h var byte
i var byte
j var byte
t var byte

for t = 1 to 100

random a

c= (a//6)+1

if c = 1 then f=f+1
if c = 2 then g=g+1
if c = 3 then h=h+1
if c = 4 then i=i+1
if c = 5 then h=h+1
if c = 6 then j=j+1
if c = 7 then k=k+1
next

debug ? f
debug ? g
debug ? h
debug ? i
debug ? j



__________________________________________________________

When it runs I ALWAYS get the same results:

f = 26
g = 19
h = 27
i = 18
j = 10


Even when I unplug the stamp, close the program, re-open etc... I get the same results. At least I get 100 results.....

Thanx in advance..

Comments

  • ZootZoot Posts: 2,227
    edited 2009-04-15 12:51
    And you will -- RANDOM is a pseudo random generator that operates on a value (shuffling it). At startup, the value of all variables is 0, so the same iterations of RANDOM will produce the same results. In fact, the process of generating truly random numbers on a computer or microcontroller is not nearly as easy as you would think.

    A better approach might be to hook up a simple light sensing circuit (photoresistor) and use RCTIME to read the value ONCE at start up. Even in similar lighting conditions, this value will never be exactly the same. Use that as your RANDOM seed (your variable a) and you should get better random results.

    The idea here is to get some kind of "more" random numbers for the outside world, which can be quite random smile.gif There are other methods too, like using an RC circuit with a temperature sensitive resistor, etc., but the light sensor trick will probably do what you want.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    When the going gets weird, the weird turn pro. -- HST

    1uffakind.com/robots/povBitMapBuilder.php
    1uffakind.com/robots/resistorLadder.php
Sign In or Register to comment.