Unit 3 Section 15 - Random Variables Part 2
Syntax
In collegeboard psudo-code RANDOM(a, b) is used to generate a random integer value in the range from a to b. For example if RANDOM(1, 5) is written 1, 2, 3, 4, and 5 have the same chance to show up. In Python the random library can be imported and the min and max ranges can be set to any integer.
import random ## The random library must be imported to use it's functions
## Either randint or randrange can be used the only difference is that you can use a step function in randrange and the max value won't be inclued
x = 0
a = 0
b = 100
while x < 10:
print ('-----')
x = x + 1
i = random.randint(a, b)
r = random.randrange(a, b, 10)
print(i, r)
randint
A general way to to write this is randint(start, stop) where start is the minimum value, stop is the maximum value. And this allows you to generate a random integer from a set range and this can help you create code for things like a coin-flip, dice roll, and anything else which needs an inclusive range.
numRolls = 10
x = 0
while x < numRolls:
x = x + 1
i = random.randint(1, 6)
print(i)
randrange
In general randrange can be written like randrange(start, stop, step) where start is the minimum value, stop is the maximum value (like the randint function), and step is the incriment the values can be and its default value is 1. If start = 0 and step = 5 all the values that can by outputed are 0 and multiples of 5. And if start = 2 and step = 3 the output would be 2 and a multiple of 3 plus 2.
x = 0
while x < 10:
x = x + 1
r = random.randrange(2, 30, 3)
print(r)
For the outputs above (except 2) if you were to subtract 2 from them you would get a multiple of 3.
A person is playing a game of darts.
This incomplete code segment simulates the person throwing a dart:
Which of these can replace MISSING CONDITION so that the has a 75% chance of making the shot? (There are TWO answers!)
- RANDOM(1, 100) <= 75
- RANDOM(1, 100) < 75
- RANDOM(1, 4) < 3
- RANDOM(1, 4) <= 3
Answer
1 and 4 are both correct, 1 includes the values from 1-75 which means that it has a 75% chance to be chosen and 4 includes the values of 1, 2, and 3 which makes 3/4 which is the same as a 75% chance.There is a 3x3 grid which randomly generates a point based on the following code:
What are the possible locations a point can be? (X is the location of the point)
x x - x x - - - - x x x x x x - - - x x - x x - x x - x x x x x x x x x