Setting random seed for reproducibility in NumPy - Time & Space Complexity
We want to understand how setting a random seed affects the time it takes to generate random numbers.
Does fixing the seed change how long the code runs as we ask for more random numbers?
Analyze the time complexity of the following code snippet.
import numpy as np
np.random.seed(42)
random_numbers = np.random.rand(1000)
This code sets a fixed seed for the random number generator and then creates 1000 random numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Generating each random number in the array.
- How many times: Once for each of the 1000 numbers requested.
As we ask for more random numbers, the time to generate them grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 random number generations |
| 100 | About 100 random number generations |
| 1000 | About 1000 random number generations |
Pattern observation: Doubling the number of random numbers roughly doubles the work done.
Time Complexity: O(n)
This means the time to generate random numbers grows linearly with how many numbers you want.
[X] Wrong: "Setting the random seed makes generating random numbers faster or slower."
[OK] Correct: Setting the seed only fixes the sequence of numbers, it does not change how many operations are needed to generate them.
Understanding how random number generation scales helps you explain performance when working with simulations or data sampling.
"What if we generate random numbers in a loop instead of all at once? How would the time complexity change?"