Random choice¶
Sometimes it is useful to take a random choice between two or more options.
Numpy has a function for that, called random.choice
:
Say we want to choose randomly between 0 and 1. We want an equal probability of getting 0 and getting 1. We could do it like this:
If we do that lots of times, we see that we have a roughly 50% chance of getting 0 (and therefore, a roughly 50% chance of getting 1).
Run the cell above a few times to confirm you get numbers very close to 0.5.
Another way of doing this is to use np.random.choice
.
As usual, check the arguments that the function expects with np.random.choice?
in a notebook cell.
The first argument is a sequence, like a list, with the options that Numpy should chose from.
For example, we can ask Numpy to choose randomly from the list [0, 1]
:
A second size
argument to the function says how many items to choose:
By default, Numpy will chose each item in the sequence with equal probability, In this case, Numpy will chose 0 with 50% probability, and 1 with 50% probability:
If you want, you can change these proportions with the p
argument:
There can be more than two choices:
The choices don’t have to be numbers:
You can also do choices without replacement, so once you have chosen an element, all subsequent choices cannot chose that element again. For example, this must return all the elements from the choices, but in random order: