Meant to be learnt via Flash Cards. Its important to quickly try things out.

Flashcards, Random Number Generation

We will start with some simple examples using the random module and then move on to the np.random module, not that this one was more complex.

Singular values:

generate a random integer

import random

min_int = 0
max_int = 10

rand_int = random.randint(min_int, max_int) # returns an integer equals to or in between min_int and max_int.

generate a random float

{python} .uniform(...)stands for the uniform distribution, meaning all values in that range have the same chance to be choosen.
import random

min_fp = 0
max_fp = 10

rand_floating_point = random.uniform(min_fp, max_fp) # returns a floating point between min_fp and max_fp

For non normal distributions I would immediately use numpy functions.

More than one value:

Once you start introducing shapes immediately move onto the np.random module.

generate random integers with a certain shape

import numpy as np

min_value = 0
max_value = 10

rand_ints = np.random.randint(low=min_value, high=max_value, size=(2,3))
# output will be a np 2x3 array with random integers between or including low and high.

generate random floating points with a certain shape

import numpy as np

min_value = 0
max_value = 10

rand_fp = np.random.uniform(low=min_value, high=max_value, size=(2,3))
# output will be a np 2x3 array with random integers between or including low and high.

generate n points with a normal distribution

import numpy as np
import matplotlib.pyplot as plt

n = 10000
center = 1 # center of normal distribution
std_dev = 1 # standard deviation

values = np.random.normal(loc=center, scale=std_dev, size=(n)))

Pasted image 20250113170944.png

Make the results reproducible

Often, we want to be able to compare our results with others. Therefore they need to generate the same "random" numbers as we do.

The seed value is actually inconsequential. It just needs to the same for everyone.

import random

# if two people execute the same code, with the same seed, then the results will be the same. 
random.seed(42)
import numpy as np

np.random.seed(43)