Random Bits
searchfgold6789
Posts: 6
I am having trouble understanding the RANDOM command in Basic Stamp Programming.
I am trying to simply generate a random number from 0 to 1, store it in a variable, and do it again in the same variable.
Is this possible?
I am trying to simply generate a random number from 0 to 1, store it in a variable, and do it again in the same variable.
Is this possible?
Comments
When people need fractional values on an integer-only device, they usually use scaled arithmetic where they use integers to represent values with decimal points. For example, you can use 1534 to represent the fixed point value 15.34. The Stamp doesn't keep track of the number of decimal places. You have to do that and you have to explicitly provide for scaling when you multiply or divide these values together or change the number of decimal places. You also have to be careful of overflows since all arithmetic (including intermediate results) is done using 16 bit values.
What do you want to do with your "random" number?
You do that by using the RANDOM statement on a variable, say Rand, and then using (Rand >>15) for your value.
Rand will be in the range 0-32767 half the time and in the range 32768-65535 half the time. (Rand >> 15) is a 0 for the range 0-32767 and a 1 for 32768-65535.
'{$STAMP BS2}
heads VAR WORD
tails VAR WORD
forum VAR WORD
'recount VAR BYTE
flip VAR WORD
heads = 0
tails = 0
flip = 0
'FOR recount = 1 TO 20
FOR forum = 1 TO 50000
DEBUG HOME
RANDOM flip
IF (flip >> 15) < 32767 THEN
DEBUG "Heads"
LOW 3
HIGH 2
heads = (heads + 1)
ELSE
DEBUG "Tails"
LOW 2
HIGH 3
tails = (tails + 1)
END IF
NEXT
DEBUG CR, ? heads, CR
DEBUG ? tails
'NEXT
LOW 2
LOW 3
END
I get What does that mean?