Random Number Generator
|Syntax:||random( seed )|
|Description:||Generates a random number using the seed number.|
|Parameters:||seed||A number which is used to generate a pseudo random number. The seed number should be an integer in the range -32768 to +32767. The number should be a different number each time it is used.|
|Returns:||Pseudo Random number in the range -32768 to +32767|
The random() command generates a random number in the range -32768 and +32767. It is typically used to provide a random element to your mpy program, to give it less predictability. In this example the LED will flash on and off with a random time.
pindir(P1_0,OUT) # Set port P1_0 as an output (Launchpad red led)
r = 0 # variable r is the intial seed (value not important)
while 1: # do forever
out(P1_0, 1) # turn the led on
wait(100) # The led will flash on for a short 0.1sec period
out(P1_0, 0) # set the output pin P1_0 (red led) to a 0 (off)
r = random( r ) # get a random number, using the seed variable r
wait(r/10) # wait for a random time of r/10 (r can be + or - value)
In this example the variable r is used as the seed to the random() command. The random number generated is between -32768 and +32767 and the number is stored back into variable r again. The random number r is used as the the wait delay divided by 10. So the LED will stay off for a period of time that is r divided by 10, (which is a delay between 0 and 3.2 seconds). This program will randomly flash the red LED.
A different seed number should be used each time the random() command is used, and if the seed number is not changed then the random number produced will be the same each time. It is typical to use the number produced in the random() command as the seed value for the next random() command. That is why in the above example variable r is re-used.
Oftentimes a random number from -32768 to +32767 is not what is wanted. If for instance the you want a random number from 0 to 99, you can use the % modulo math function: r % 100 This calculates the remainder value which will be in the range of 0 to 99.
r = 0
r = random(r)
r100 = r % 100
print ' a random number between 0 and 100 is ', r100
The random() command is not a true random number generator, the random number is generated using a simple mathmatical formula.
S = ( ( (S>>1) * (-18121) ) + 359 )
Because numbers in mpy are signed 16bit integers, the result of the sum will overrun and produce a number in the range of -32768 to +32767 whose value is somewhat random.