Simulation and Randomness
Some questions cannot be answered by looking something up, because the answer depends on things that have not happened yet and that vary by chance: how many pastries to bake when the number of customers changes from day to day, or whether one person at a service desk is enough when people arrive in bursts. For a few such questions there is a formula; for most there is not. A simulation works regardless: build a small model of the situation, let the computer live through it thousands of times, and count what happens. A computer cannot produce chance, so its random numbers are pseudorandom — a sequence fixed entirely by its seed — and that is a feature, because a result that cannot be repeated cannot be checked or debugged. The discipline is one generator, made once from a seed and passed to every function that draws; a generator created inside the loop restarts the sequence, and every trial becomes the same trial.
Simulation also brings a difficulty nothing earlier in the course had: run the program again and the answer changes. A simulated number is an estimate, so it comes with a standard error and an interval, both computable from a single run. The error shrinks with the square root of the number of trials — a hundred times the work buys one more decimal place — which gives “how many trials?” an answer: enough that the interval is narrower than the difference you care about. To compare options fairly, give each exactly the same random draws, so the luck is in both results and cancels out of the difference. The same machinery, pointed at real data, is the bootstrap: resample the sample, with replacement, to see how far its mean or median would move. Report the estimate with its interval, its number of trials, its seed, and its assumptions; the simulation answers the model, not the world.

Listen
| Speaker | Text |
|---|---|
| Alex | So imagine you just wrote like this totally flawless Python script. Your panda’s data frames merge perfectly. There is literally not a single syntax error and your math, it just checks out down to the last decibel. |
| Sam | Oh yeah, that is, uh, that’s a great feeling, right? |
| Alex | It’s the best. So you hand this resulting report to a VP. And they base a massive, you know, million dollar supply chain decision on it. And then, well, it completely blows up in their face. |
| Sam | Ouch, yeah, |
| Alex | we’ve all been there. The company loses money. And you’re just left staring at your Jupiter notebook, wondering where it all went wrong. Because the reality is your code was actually perfect. |
| Sam | It’s just that you used it to query a database for what happened last quarter instead of, you know, simulating what could happen tomorrow. |
| Alex | Exactly. And welcome to today’s deep dive. If you’re a data science grad student, you know, deep in the Python trenches right now, that is the exact pivot you eventually have to make. |
| Sam | It really is the crucial pivot because historical data, it’s comfortable. It’s, well, it’s basically a fossil record, right? The numbers just sit quietly in a CSV file and your job is essentially forensic. You’re just calculating the mean of an event that already took place, which is easy, |
| Alex | but boardroom decisions. Whether that’s financial planning, inventory management, or staffing, they require stepping into the unpredictable future, |
| Sam | right? And traditional formulas, they just hit a wall the moment human behavior and chance enter the equation. Yeah, |
| Alex | you really can’t write a clean algebraic equation for like how many customers are going to walk into a bakery on a Tuesday when it might rain. |
| Sam | Or whether a sudden influx of tickets will just totally overwhelm a campus help desk, |
| Alex | right? The variables interact in ways that just become mathematically intractable, |
| Sam | which is why we abandon the quest for a perfect mathematical formula and we trade it for raw computing power. I love that trade, right? So today we’re exploring the architecture of simulations. Instead of trying to calculate the exact probability of an outcome. We build this, this sort of digital terrarium in Python, |
| Alex | a digital terrarium, yeah, |
| Sam | we model the rules of the business, force the computer to live through that scenario tens of thousands of times, and then we analyze that simulated data using the exact same statistical tools we use on historical data. |
| Alex | So we are essentially turning Python into a laboratory for business experiments. Exactly. We can manipulate configuration parameters like Pricing or staffing levels and observe their downstream effects before spending a single real |
| Sam | world dollar, which is huge for businesses, |
| Alex | huge. So let’s get into the mechanics of this, starting with, uh, the engine of basically any simulation, which is Monte Carlo methods, right? |
| Sam | Monte Carlo. |
| Alex | The premise here is that we need to generate random chance inside a CPU, which is, you know, a piece of hardware designed to be rigidly logical and predictable. |
| Sam | Yeah, to run an experiment thousands of times, you have to synthesize chaos, |
| Alex | synthesize chaos, right? |
| Sam | And a classic introductory application is rolling two virtual dice to see how often they total 7. Mathematically, there are 6 combinations out of 36 that make a 7, so the true probability is 16.67%. |
| Alex | But in a Monte Carlo simulation we don’t actually do the math. |
| Sam | No, not at all. But we just command Python to roll two dice 10,000 times, count the sevens, and divide by 10,000, |
| Alex | and the outcome will hover incredibly close to 16.67%. Exactly. But, OK, as data practitioners, we know that computers can’t actually roll dice. Like there’s no physical entropy happening inside the processor, |
| Sam | right? |
| Alex | The machine is just following a strict algorithm to spit out numbers, so. If the randomness isn’t actually random, how do we justify building massive business models on top of it? Well, |
| Sam | we justify it because the numbers are pseudo random, and that pseudo prefix is actually our greatest asset here. |
| Alex | OK, unpack that a bit. |
| Sam | So the generator uses a mathematical recipe. It takes a starting value, scrambles it through a highly complex kind of cryptographic style algorithm, and produces a sequence of numbers that is statistically indistinguishable from pure chance for our modeling purposes. And that starting value, that’s called the seed. |
| Alex | The seed, yeah, I think a lot of people conceptualize the seed as just this chaotic kickstart, but a better analogy is like a treasure map starting coordinate. Oh, I like that. Yeah. So if you start at the exact same GPS coordinate, the seed. And follow the exact same list of complex directional steps, you will always end up at the exact same destination traversing the exact same path. |
| Sam | That is a perfect way to frame it, and that deterministic nature is a feature, not a bug. Like if you initialize your numpii generator with, say, NP. random.default RNG and you pass it 8410 you lock in that treasure map exactly every single time you run that script on any computer in the world, you get the identical sequence of random numbers |
| Alex | because without that fixed seed, a simulation is completely useless in a professional environment. |
| Sam | Totally useless. You can’t debug a failure that happens on iteration 4000 if you can’t recreate iteration 4000. Yeah, |
| Alex | but business couldn’t audit your findings and your peers couldn’t verify your logic, |
| Sam | right. And if you leave the seed blank, the computer typically pulls the current microsecond from the system clock to use as a starting point, |
| Alex | which means your sequence is gone forever the moment the script finishes running. Poof, gone. So establishing that reproducible string of numbers is step one, but the architecture of how we handle that generator inside our Python code, and that’s where I see a lot of people introduce these silent catastrophic failures. Oh, |
| Sam | absolutely. The architecture of your code completely dictates the validity of your statistical output. A robust simulation isolates concerns. You have the random number generation, let’s call it the draw demand function. And you have your arithmetic, perhaps a calculate profit function, |
| Alex | and mixing these two together in one massive block of code is a recipe for untestable models. |
| Sam | It really is |
| Alex | because you want to be able to feed hardcoded fake numbers into your calculate profit function to verify the math by hand, right? |
| Sam | Exactly. Once you know the arithmetic is bulletproof, then you hook up the random generator. But |
| Alex | the real danger isn’t untestable arithmetic. I want to talk about loop placement. |
| Sam | Oh, |
| Alex | yes, a very common habit when writing a Monte Carlo script is to set up a loop, say, for I in range 10,000, and then instantiate the generator with its seed inside that loop. It feels self-contained, |
| Sam | and doing that completely invalidates the entire simulation without throwing a single syntax error. |
| Alex | It’s terrifying. |
| Sam | It is. Think about the mechanical flow of the Python interpreter. On loop iteration 0, Python sets the seed, draws the first number from the sequence and calculates an outcome. On loop iteration 1, Python sets the exact same seed again, draws the exact same first number and produces the exact same outcome. |
| Alex | So you didn’t run 10,000 independent trials. You ran the identical trial 10,000 times. Exactly. Your variance drops to zero and the standard error of your estimate becomes artificially perfect. |
| Sam | It is a devastating silent failure. |
| Alex | Like you will take this result to a stakeholder supremely confident in your tight confidence interval, and you will be completely wrong. |
| Sam | Yeah, the generator must be instantiated exactly once at the very top of your script outside of any loops. You pass that generator object into your functions. Every time a function calls it, the generator advances one step forward in its internal state, giving you a fresh independent number for your trial. |
| Alex | OK, while we’re on the subject of silent failures that ruin probability distributions. There is a notorious pitfall involving how different Python libraries handle the bounds of random integers. Oh, |
| Sam | the standard library versus numpi. |
| Alex | Yes, for grad students, zero indexing and inclusive versus exclusive bounds are usually second nature, but in the context of simulation, mixing them up is deadly. It’s a |
| Sam | classic trap. It is. If you are simulating a six-sided die in numpi, the syntax is rng.integers 17. Numpai treats the upper bound as exclusive. It stops at 6, |
| Alex | right? But the Python Standard Library’s random.randin 1.6 treats the upper bound as inclusive. |
| Sam | Exactly. So if you accidentally use numpi and write RNG.integers 1.6, you aren’t going to get an index out of bounds crash. No, |
| Alex | your code will run beautifully, |
| Sam | beautifully, but you have Secretly simulated a five-sided |
| Alex | die, which is insane. You’ve structurally eliminated a massive chunk of probability from your model, |
| Sam | and your calculated average will be totally skewed, and you won’t know why until the real-world results fail to match your prediction, right? |
| Alex | Knowing your tools at a granular level is non-negotiable. But OK, let’s assume the architecture is flawless. The loop is correct, the bounds are accurate, the seed is set. Sounds good. You simulate a bakery’s daily profit 10,000 times, and you get an average. Because it’s a Monte Carlo model, if you change the seed and run it again, you get a slightly different average. You run 20 seeds, you get 20 different answers. The CEO asks for the final number. How do you respond? You tell them there is no single number. Good answer. |
| Sam | Yeah. Handing an executive a raw point estimate from a simulation is, well, it’s borderline statistical malpractice. It |
| Alex | really is. A simulated outcome is just an estimate drawn from a distribution. And it must be presented with a statement of its own uncertainty, |
| Sam | which we quantify using the standard error. You calculate that by taking the standard deviation of your simulated outcomes and dividing it by the square root of your number of trials, |
| Alex | and that gives us our confidence interval. Exactly. So practically speaking, instead of saying a The estimated profit is $1500. You report the estimated profit is $1500 and we are 95% confident the true average falls between $1450 and $1550. |
| Sam | And we need to be very precise about what a 95% confidence interval actually means in this context. |
| Alex | OK, let’s clarify that. It |
| Sam | is a claim about the reliability of your simulation methodology. It means if you were to repeat this entire 10,000 trial simulation over and over with different seeds, 95% of the intervals you generate would successfully capture the true theoretical mean of your model, |
| Alex | which means 5% of the time your interval misses the mark completely. That’s just the cost of doing business with probability. But, uh, the formula you just mentioned for standard error dividing by the square root of the number of trials. That has massive implications for computational cost. Oh, |
| Sam | it dictates the entire economics of precision because of that square root relationship. The standard error shrinks incredibly slowly as you add more trials, |
| Alex | right? If I want to cut my error margin in half, I can’t just double my computing time. I have to multiply my trials by 4. And if I want a 10th of the error margin, like just one more decimal place of accuracy. I have to run 100 times the number of trials. It |
| Sam | very quickly becomes a question of diminishing returns. |
| Alex | It’s heavily analogous to screen resolution, actually. Oh, how so? Well, upgrading from a 1080p television to a 4K display requires the graphics processor to push 4 times as many pixels, right? The hardware cost is exponentially higher. But when you’re sitting 10 ft away on your couch, the human eye barely registers the sharper image. |
| Sam | That’s a great point. |
| Alex | At a certain point, the extra precision just isn’t actionable. So, for a data practitioner spinning up an AWS instance, how many trials is actually enough? |
| Sam | Well, the threshold is defined by the business decision, not by mathematical perfection. You run enough trials so that your confidence interval is narrower than the monetary difference the business actually cares about. Like if a variation of $50 in daily profit isn’t going to change whether the CEO approves the project, you don’t need to burn cloud computing budget running 10 million trials to get sub-dollar precision. |
| Alex | Basically, don’t pay for 4K rendering if the boardroom only needs a 1080p picture to make a choice. Exactly. And making choices between competing strategies is the entire goal here. So let’s look at the umbrella problem as a framework for this. A retail shop is trying to decide whether to stock 22 umbrellas or 23 for the upcoming rainy season. |
| Sam | Now in the physical world, testing this is incredibly difficult. You might try an A B test, stock 22 this month, stock 23 next month. But if month 1 has a freak weeklong storm and month 2 is a drought, the variance in the weather completely drowns out the signal of your inventory decision. |
| Alex | The day’s random luck just ruins the test. Exactly. But in a Python simulation, we can control the universe. We can hold luck constant. |
| Sam | We use a technique called common random numbers. Mathematically, what we are trying to do is minimize the variance of the difference between the two strategies. OK, break that down. By generating our random weather demand exactly once, creating an array of 10,000 simulated days of weather. We ensure the external conditions are identically applied to both options. Oh, |
| Alex | I see. So we run strategy A 22 umbrellas through those exact 10,000 days. Then we rewind the tape. And runs strategy B 23 umbrellas through the exact same 10,000 days. Monday is identically chaotic for both models. Saturday is identically dry. |
| Sam | Yes, the variance caused by the luck of the weather is present in both results. So when you subtract the profit of strategy A from strategy B, that shared variance effectively cancels out in statistical. Terms, the covariance between the two strategies becomes very large and positive, which drastically shrinks the standard error of the difference between them. That makes total sense. Common random numbers allow you to detect a microscopic business advantage that would be utterly invisible in a real world pilot program. |
| Alex | It is brilliant. You are basically creating a multiverse where only your configuration parameter changes exactly. And this variance cancellation technique is critical for more complex models too, like queuing theory. There’s a classic help desk scenario that illustrates why we can’t just rely on averages for capacity planning, |
| Sam | right? Queuing systems are notoriously hostile to simple algebra. Yeah. Suppose a campus IT desk gets a visitor on average every 4 minutes, and the time it takes to resolve a ticket averages 3.5 minutes. On paper, one worker at the desk has excess capacity, right? 4 minutes is greater than 3.5. |
| Alex | The spreadsheet says the queue will be 0. Exactly. |
| Sam | But averages hide the reality of variance. People don’t arrive on a perfectly spaced metronome schedule. |
| Alex | No, a lecture ends and 6 people show up simultaneously, right? |
| Sam | And a password reset takes 30 seconds, but a hard drive failure takes 40 minutes, |
| Alex | right? |
| Sam | When you build the simulation and introduce that bursty random variance, the system collapses. The model reveals that a single worker will routinely generate hour-long queues, even though their average utilization looks perfectly fine. |
| Alex | This is the essence of sensitivity analysis. As a system approaches its maximum capacity. Wait times do not scale linearly. They scale exponentially. Yes. |
| Sam | And when you apply common random numbers to test adding a second worker on those exact same simulated chaotic days, the wait time doesn’t just drop by 50%. |
| Alex | No, it collapses from 1 hour down to under 1 minute, |
| Sam | right? The simulation exposes the nonlinear breaking point of the business that algebraic averages completely obscured. |
| Alex | It is so powerful. But you know, all of this assumes we are drawing our randomness from theoretical distributions like a Poisson distribution for arrivals or a normal distribution for tas duration. |
| Sam | Yeah, we are assuming we know the underlying mathematical shape of reality, |
| Alex | but often we don’t. No, |
| Sam | we don’t, |
| Alex | which brings us to the final major hurdle. What happens when you don’t have a theoretical distribution? You just have a single messy real-world data set. Let’s say you surveyed 2000 actual customers about how much they’re willing to pay for a new software tier. You calculate the average, but you need to know how much that average would fluctuate if you had somehow surveyed a different 2000 people, and you |
| Sam | can’t afford to run the survey again. Exactly. So we use an empirical resampling technique known as the bootstrap. |
| Alex | The bootstrap, the mechanism of the bootstrap always feels a bit like a magic trick to me. It really does. Like you take your existing sample of 2000 surveys. And you draw a new sample of 2000 from it entirely at random with replacement, right, |
| Sam | with replacement, that’s the key, |
| Alex | because you were putting the survey back in the pool after each draw, your simulated sample might include customer A 3 times and customer B 0 times. You calculate the average of this weird shuffle data set and you repeat this process 10,000 times, |
| Sam | and the skepticism here is completely understandable. You aren’t creating new information out of thin air, right? The mathematical mechanism relies on a very specific assumption, which is that the internal variation of your sample is a highly accurate proxy for the internal variation of the entire unobserved population. Oh, |
| Alex | I see. It’s like assuming our sample of 2000 is a high resolution photograph of the broader world. Exactly. By shuffling the pixels around with replacement, we are mimicking the process of drawing a fresh sample from the real world. We are asking the data basically. Is our average stable across the whole group, or is it being yanked around by three extreme outliers? |
| Sam | It reveals the spread of your data without requiring complex calculus. You can bootstrap medians, variances, or bizarre custom metrics that have no standard mathematical formula, |
| Alex | but this relies on a dangerous assumption, right? Yes, |
| Sam | the vulnerability of the proxy. The bootstrap is structurally blind to what it has never seen. If the population distribution is heavy-tailed, meaning there are rare extreme giants out there, and by pure bad luck, your original sample of 2000 failed to capture even one of them, well, the bootstrap cannot save you. |
| Alex | So if you are surveying net worth and your empirical sample doesn’t accidentally catch a billionaire, Resampling with replacement 10,000 times will never reshuffle a billionaire into existence. |
| Sam | Never. Your simulation will output a beautifully tight confidence interval. It will look statistically bulletproof, and it will confidently fail to contain the true real world mean. An algorithm. The can perfectly report its own internal uncertainty but still be catastrophically wrong if the original sample didn’t capture the extremes of reality, |
| Alex | which really brings a certain humility to the job, doesn’t |
| Sam | it? It absolutely does. |
| Alex | You can write the cleanest Python code in your cohort, you know, carefully manage your seeds, isolate your architecture, and apply common random numbers perfectly. But before you hand the report to the boardroom. You have to realize what you’re actually handing them. |
| Sam | Yes, you need to provide the estimate, the confidence interval, the trial count, the seed so they can audit it, and your assumptions. |
| Alex | The assumptions might be the most important deliverable. They are. |
| Sam | There is a saying in modeling, the simulation answers the model, not the world. |
| Alex | Oh, I like that. The simulation answers the model, not the world. Because you perfectly solved the terrarium, but the terrarium is just a shadow of the actual business environment. |
| Sam | It is a highly optimized approximation, |
| Alex | and treating an approximation as absolute truth is where organizations lose millions of dollars, which leaves us with a final thought to mull over as you spin up your environments tomorrow. Let’s hear it. Analyzing historical data is like studying a fossil. The event is over, it can’t be changed, but a simulation tries to map the future and in business. The future reacts to your decisions. If your perfect model tells the CEO to slash help desk hours or hike bakery prices, and the company executes that strategy, the real world consumers are going to notice and |
| Sam | they will change their behavior. The rules of the system shift dynamically. |
| Alex | The moment the business implements the winning strategy from your simulation, they alter the very reality the simulation was trying to predict. |
| Sam | It creates a new reality that renders the model obsolete. |
| Alex | So, keep your seats fixed, mind your Python bounds, and always remember that no confidence interval can protect you from a shifting world. |
Presentation
Read
- Simulation and Randomness (lecture notes)
Hands-on
Notebooks in 10-Simulation-Randomness
Homework
- Homework 9: An Answer with Error Bars — due Wednesday, November 11, 2026