LESSON 08 – RANDOM
NUMBER RANDOMNESS IN PROGRAMS It
is often useful to generate a random number in order to give your
program/circuit a random behavior or starting point. BUILT-IN FUNCTION One
can use the random function to get a random number. There are two versions of this function. VERSION 1 – MAX ONLY In
this version, one can generate a random number between 0 and max (exclusive). Here
is an example of generating a number between 0 and 99. int randomNumber; randomNumber =
random(100); VERSION 2 – MIN &
MAX In
this version, one can generate a random number between min and max. Here
is an example of generating an numberbetween 20 and
29: int anotherRandomNumber; anotherRandomNumber
= random(20,30); EXCLUSIVENESS OF MAX Notice
that the max is excluded from the possible range of numbers. So if you wanted to generate a number from
0 to 100 that could include 100, then you’d use int randomNumber
= random(101); RANDOM SEED If
it is important for a sequence of values generated by random()
to differ, on subsequent executions of a program, use randomSeed()
to initialize the random number generator with a fairly random input, such as
analogRead() on an unconnected pin. EXAMPLE Inside
setup(), you would use: randomSeed(analogRead(0)); where 0 is any pin that is floating as it will give a fairly
unpredictable value. REPEATED RANDOMNESS It
can occasionally be useful to use pseudo-random sequences that repeat
exactly. This can be accomplished by calling randomSeed() with a fixed
number, before starting the random sequence. EXAMPLE Inside
setup(), use randomSeed(1000); where 1000 could be any number. |
TRY THIS… PRACTICE 10 Write a program that will
continuously generate a random number between 0 and 10 and output it to
screen. Include a reasonable delay. ALTERATIONS Create two global
variables called belowFive and aboveFive.
They will count the number of random numbers that are either below (0
to 4) or above five (5-9). Their
totals should be outputted evere 100th number. |