Bird
Raised Fist0
NumPydata~10 mins

Random sampling distributions in NumPy - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Random sampling distributions
Choose distribution type
↓
Set parameters (mean, std, etc.)
↓
Generate random samples
↓
Calculate sample statistics
↓
Visualize or analyze samples
↓
Repeat for multiple samples
↓
Observe sampling distribution behavior
This flow shows how to pick a distribution, generate random samples, and analyze their statistics to understand sampling distributions.
Execution Sample
NumPy
import numpy as np
samples = np.random.normal(loc=0, scale=1, size=5)
mean_sample = np.mean(samples)
print(samples, mean_sample)
Generate 5 random samples from a normal distribution and calculate their mean.
Execution Table
StepActionCode/OperationResult/Value
1Import numpyimport numpy as npnumpy module ready
2Generate 5 samples from normal distributionsamples = np.random.normal(loc=0, scale=1, size=5)[0.5, -1.2, 0.3, 1.1, -0.7] (example)
3Calculate mean of samplesmean_sample = np.mean(samples)Mean = 0.0 (example)
4Print samples and meanprint(samples, mean_sample)[0.5, -1.2, 0.3, 1.1, -0.7] 0.0
5End of executionN/ASampling and mean calculation done
💡 All steps executed; samples generated and mean calculated.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
samplesNone[0.5, -1.2, 0.3, 1.1, -0.7][0.5, -1.2, 0.3, 1.1, -0.7][0.5, -1.2, 0.3, 1.1, -0.7]
mean_sampleNoneNone0.00.0
Key Moments - 3 Insights
Why do the random samples change every time we run the code?
Because np.random.normal generates new random numbers each run, the samples differ. This is shown in execution_table step 2 where samples are created.
Is the mean of the samples always exactly zero for a normal distribution with mean 0?
No, the mean of a small sample varies due to randomness. The execution_table step 3 shows the calculated mean from the sample, which can differ from zero.
What does the 'size' parameter control in np.random.normal?
It controls how many random samples are generated at once, as seen in step 2 where size=5 means 5 samples are created.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 2. What does the 'samples' variable contain?
AA list of 5 random numbers from a normal distribution
BA single random number
CThe mean of the samples
DAn empty list
💡 Hint
Check the 'Result/Value' column in step 2 of execution_table.
At which step is the mean of the samples calculated?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for the action 'Calculate mean of samples' in execution_table.
If we increase the 'size' parameter to 1000, what changes in the execution_table?
AThe samples will be all zeros
BThe mean calculation step will be skipped
CThe samples array will have 1000 numbers instead of 5
DThe numpy import will fail
💡 Hint
Refer to the 'size' parameter effect in step 2 of execution_table.
Concept Snapshot
Random sampling distributions:
- Use numpy.random functions (e.g., normal, uniform)
- Specify parameters like mean (loc), std (scale), and sample size
- Generate samples with np.random.normal(loc, scale, size)
- Calculate sample statistics (mean, std) with numpy
- Sampling distributions show variability in sample stats
- Useful for understanding data randomness and inference
Full Transcript
This lesson shows how to generate random samples from a distribution using numpy. First, we import numpy. Then, we generate 5 random numbers from a normal distribution with mean 0 and standard deviation 1. Next, we calculate the mean of these samples. Finally, we print the samples and their mean. Each run produces different samples because of randomness. The mean of a small sample can vary from the true mean. The size parameter controls how many samples are generated. This process helps us understand how sample statistics vary in random sampling.

Practice

(1/5)
1. What does the numpy.random.choice function do in random sampling?
easy
A. It selects random elements from a given array or list.
B. It generates random numbers from a normal distribution.
C. It creates a sequence of numbers with equal spacing.
D. It calculates the mean of a dataset.

Solution

  1. Step 1: Understand the purpose of numpy.random.choice

    This function is used to randomly pick elements from an input array or list, optionally with replacement.
  2. Step 2: Compare with other options

    Options A, B, and C describe different numpy functions or operations unrelated to random selection from an array.
  3. Final Answer:

    It selects random elements from a given array or list. -> Option A
  4. Quick Check:

    numpy.random.choice = random selection [OK]
Hint: Remember: choice picks from arrays, normal generates bell curve numbers [OK]
Common Mistakes:
  • Confusing choice with normal distribution generator
  • Thinking choice creates sequences
  • Assuming choice calculates statistics
2. Which of the following is the correct syntax to generate 5 samples from a binomial distribution with 10 trials and success probability 0.3 using numpy?
easy
A. numpy.binomial(10, 0.3, 5)
B. numpy.random.binomial(10, 0.3, size=5)
C. numpy.random.binomial(size=5, 10, 0.3)
D. numpy.random.binomial(5, 10, 0.3)

Solution

  1. Step 1: Recall the numpy binomial function signature

    The correct syntax is numpy.random.binomial(n, p, size) where n is number of trials, p is success probability, and size is number of samples.
  2. Step 2: Check each option

    numpy.random.binomial(10, 0.3, size=5) matches the correct order and uses the keyword size. numpy.binomial(10, 0.3, 5) misses .random. numpy.random.binomial(size=5, 10, 0.3) mixes keyword size=5 followed by positionals, causing SyntaxError. numpy.random.binomial(5, 10, 0.3) swaps parameters incorrectly.
  3. Final Answer:

    numpy.random.binomial(10, 0.3, size=5) -> Option B
  4. Quick Check:

    binomial(n, p, size) = numpy.random.binomial(10, 0.3, size=5) [OK]
Hint: Remember order: trials, probability, then size keyword [OK]
Common Mistakes:
  • Mixing argument order
  • Omitting size keyword
  • Using wrong function name
3. What is the output of the following code?
import numpy as np
np.random.seed(0)
samples = np.random.normal(loc=5, scale=2, size=3)
print(np.round(samples, 2))
medium
A. [7.65 5.12 6.34]
B. [8.53 4.32 6.58]
C. [8.82 4.0 6.89]
D. [8.53 5.8 6.96]

Solution

  1. Step 1: Understand the code

    The code sets a random seed for reproducibility, then generates 3 samples from a normal distribution with mean 5 and standard deviation 2.
  2. Step 2: Run or recall the output

    Using seed 0, the samples generated are [8.53, 5.8, 6.96] after rounding to 2 decimals.
  3. Final Answer:

    [8.53 5.8 6.96] -> Option D
  4. Quick Check:

    Seed 0 normal samples = [8.53 5.8 6.96] [OK]
Hint: Use seed for fixed output, then round to compare [OK]
Common Mistakes:
  • Ignoring seed causes different outputs
  • Rounding incorrectly
  • Mixing mean and scale parameters
4. Identify the error in this code snippet that tries to sample 4 values from a uniform distribution between 0 and 1:
import numpy as np
samples = np.random.uniform(low=0, high=1, size=4)
print(samples)
medium
A. There is no error; the code runs correctly.
B. The parameters low and high are reversed.
C. The function name should be random.uniform without numpy prefix.
D. The size parameter must be a tuple, not an integer.

Solution

  1. Step 1: Review the numpy uniform function syntax

    np.random.uniform(low, high, size) is the correct way to generate samples from a uniform distribution.
  2. Step 2: Check the code correctness

    The code uses correct function name, parameter order, and size as integer for 1D array. It will run without error and print 4 random values between 0 and 1.
  3. Final Answer:

    There is no error; the code runs correctly. -> Option A
  4. Quick Check:

    Uniform sampling syntax correct = There is no error; the code runs correctly. [OK]
Hint: Check function name and parameter order carefully [OK]
Common Mistakes:
  • Confusing numpy.random.uniform with Python's random.uniform
  • Swapping low and high values
  • Using tuple for size unnecessarily
5. You want to simulate rolling a fair six-sided die 1000 times and count how many times the number 4 appears. Which numpy code correctly performs this simulation?
hard
A. rolls = np.random.choice([1,2,3,4,5,6], size=1000) count_4 = np.sum(rolls == 4)
B. rolls = np.random.binomial(6, 1/6, size=1000) count_4 = np.count_nonzero(rolls == 4)
C. rolls = np.random.randint(1, 7, size=1000) count_4 = np.sum(rolls == 4)
D. rolls = np.random.normal(4, 1, size=1000) count_4 = np.sum(rolls == 4)

Solution

  1. Step 1: Understand the problem

    We want to simulate rolling a die 1000 times, each roll equally likely from 1 to 6, then count how many times 4 appears.
  2. Step 2: Evaluate each option

    rolls = np.random.randint(1, 7, size=1000) count_4 = np.sum(rolls == 4): rolls = np.random.randint(1, 7, size=1000) count_4 = np.sum(rolls == 4) uses randint from 1 to 6 (exclusive upper bound 7), perfect for die rolls. rolls = np.random.binomial(6, 1/6, size=1000) count_4 = np.count_nonzero(rolls == 4): rolls = np.random.binomial(6, 1/6, size=1000) count_4 = np.count_nonzero(rolls == 4) uses binomial which models number of successes in trials, not die rolls. rolls = np.random.choice([1,2,3,4,5,6], size=1000) count_4 = np.sum(rolls == 4): rolls = np.random.choice([1,2,3,4,5,6], size=1000) count_4 = np.sum(rolls == 4) omits replace=True (defaults to False), raising ValueError since size=1000 > 6. rolls = np.random.normal(4, 1, size=1000) count_4 = np.sum(rolls == 4): rolls = np.random.normal(4, 1, size=1000) count_4 = np.sum(rolls == 4) uses normal distribution, inappropriate for discrete die rolls.
  3. Step 3: Choose the best correct code

    rolls = np.random.randint(1, 7, size=1000) count_4 = np.sum(rolls == 4) is the correct way to simulate die rolls and count 4s.
  4. Final Answer:

    rolls = np.random.randint(1, 7, size=1000) count_4 = np.sum(rolls == 4) -> Option C
  5. Quick Check:

    Use randint for discrete uniform die rolls = rolls = np.random.randint(1, 7, size=1000) count_4 = np.sum(rolls == 4) [OK]
Hint: Use randint(1,7) for dice rolls, then count matches [OK]
Common Mistakes:
  • Using binomial instead of uniform discrete
  • Using normal distribution for discrete outcomes
  • Forgetting replace=True in choice
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard