8.8 - Random Number Generation
The purpose and uses of random numbers
Random numbers allow programs to produce unpredictable outcomes, making them essential for simulating real-world events where predictability would reduce realism or fairness.
Key applications of random numbers
- Simulating real-life events - Random numbers can model occurrences such as rolling a dice, drawing raffle tickets, or generating lottery numbers, where the outcome should not be predetermined.
- Creating engaging games - They introduce elements of surprise, ensuring that even the programmer cannot predict the result, which enhances gameplay by making it truly random.
Random numbers are generated using built-in functions in most programming languages.
Generating random numbers with functions
Programming languages provide functions to generate random numbers between defined limits. These functions can produce either integers or real numbers, depending on the input values.
Basic random number function
In pseudocode, the function random(x, y) generates a random number in the range from x to y, inclusive.
- If x and y are integers, the function returns a random integer.
- If x and y are real numbers (floats), it returns a random real number.
Examples of random number generation:
These functions ensure the generated number is unpredictable, adding realism to simulations.
Simulating events with random numbers
Random numbers can simulate chance-based events, such as rolling a dice or tossing a coin. This involves generating a number and mapping it to possible outcomes.
Simulating a dice roll
A standard six-sided dice has outcomes from 1 to 6. Use the random function to generate a number in this range and output it.
This code assigns a random value to the variable roll and displays it, mimicking a physical dice throw.
Using loops to generate multiple random numbers
Loops, such as FOR loops, can generate several random numbers in sequence, which is useful for simulations requiring multiple trials.
Note that the same number can appear more than once, as randomness allows for repetition.
Making random selections
Random numbers can drive decisions beyond direct output, such as selecting outcomes or items from a set.
Simulating a coin toss
A coin toss has two outcomes: heads or tails. Map these to random integers (e.g., 0 for heads, 1 for tails) and use an IF statement to determine the result.
This approach simplifies binary choices into a programmable format.
Using random numbers with arrays
Arrays store collections of items, and random numbers can select an element by index.
This method is ideal for random selections from lists, such as picking a winner from entries or generating varied game elements.