Random Numbers
Random Numbers
Numbers/Simulations
• Games often use random numbers to make things interesting
• Rolling Dice
• Spinning a wheel
• Pick a card
• A simulation program uses the computer to simulate an activity in the
real world (or the imaginary world).
• A simulation usually involves looping through a sequence of events
05/09/2025 1
Generating Random
Numbers
• The Python library has a random number generator that produces
numbers that appear to be random
• The numbers are not completely random. The numbers are drawn
from a sequence of numbers that does not repeat for a long time
• random() returns a number that is >= 0 and < 1
05/09/2025 2
Simulating Die Tosses
• Goal:
• To generate a random integer in a given range we use the randint()
function
• Randint has two parameters, the range (inclusive) of numbers
generated
05/09/2025 3
The Monte Carlo Method
• Used to find approximate solutions to problems that cannot be precisely
solved
• Example: Approximate PI using the relative areas of a circle inside a square.
Simulate shooting a dart into a square surrounding circle of radius 1. To do
this,
• Generate random x- and y-coordinates between -1 and 1
• If the generated point lies in the circle it is a hit (when x 2+y2 ≤ 1)
• Tries are total number of tries
• π/4 = Hits / Tries
• π = 4 x Hits / Tries
05/09/2025 4
Monte Carlo Example
05/09/2025 5
Guess Game: Guess number
1 - 100
#Program simulates a guess number game Guess a number between 1 and 100: 200
#The player is asked to guess a number bewteen 1 and 100 Your guess is outside range 1-100!
05/09/2025 6
Summary
• In a simulation, you use the computer to simulate an activity.
• You can introduce randomness by calling the random number generator.
05/09/2025 7