Tutorial 1: Simulating Random Variables
numpy · scipy.stats · Submit as dm01t[RR].py
Submission
Name your file dm01t[RR].py where RR = last two digits of your roll number. Example: roll ending in 10 → dm01t10.py. All five tasks must be in one file, with # Task N comments separating them. Submit by the deadline announced in class.
Background
In data mining we frequently simulate data, understand probability distributions, and reason about random processes. This tutorial builds the numpy/scipy foundation used throughout the course. We focus on the Bernoulli distribution (a single yes/no trial) and the Binomial distribution (count of successes across N independent trials).
Tasks
Task 1 Set Up the Random Number Generator
- Import numpy as
np - Create a generator:
rng = np.random.default_rng(seed=5) - Print the generator object to confirm creation
Task 2 Bernoulli Random Variable X with p = 0.8
A Bernoulli variable models one trial: success (1) with probability p, failure (0) with probability 1−p.
- Set
p = 0.8 - Sample 25 Bernoulli outcomes and store in a numpy array
samples:samples = rng.binomial(n=1, p=0.8, size=25) - Print the numpy vector
samples - Compute and print the average of the 25 samples using
np.mean()
Task 3 Compute the Average using numpy's Statistical Method
- Compute the sample mean:
sample_mean = np.mean(samples) - Print it formatted to 4 decimal places:
f"Sample mean: {sample_mean:.4f}" - Compute the theoretical mean of Bernoulli(p=0.8) and store as
theoretical_mean - Print the theoretical mean and the absolute difference between sample and theoretical means
Task 4 Binomial Random Variable Y with n = 10, p = 0.8
Y ~ Binomial(n=10, p=0.8) counts the number of successes across 10 independent Bernoulli(0.8) trials. Y takes values 0, 1, 2, …, 10.
- Set
n = 10,p = 0.8 - Sample 25 outcomes from Y:
Y_samples = rng.binomial(n=10, p=0.8, size=25) - Print the 25 sampled outcomes
- Compute and print the expectation (mean) of Y_samples using a numpy statistical method
- Compute and print the theoretical expectation E[Y] = n × p
Task 5 Extension: Variance (discuss in tutorial session)
- Compute sample variance of
samplesusingnp.var(samples)and print it - Print the theoretical variance of Bernoulli(p=0.8) = p(1−p)
- Compute and print sample variance of
Y_samples - Print the theoretical variance of Binomial(n=10, p=0.8) = n·p·(1−p)
- Try n=100 and n=1000 with size=25. Write a comment in your code about what happens to the sample mean relative to the theoretical mean as n increases.