Created
January 20, 2025 00:49
-
-
Save faresbakhit/a251619f1fb1709dfa84a3436a9d2fec to your computer and use it in GitHub Desktop.
"Monte Carlo Process" simulation for the example in Taylor's Introduction to Management Science textbook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections.abc import Callable | |
import random | |
def demand(x: int) -> int: | |
d = 0 | |
if not 0 <= x <= 99: | |
raise RuntimeError(f"{x=} not in [0, 100)") | |
for m in [19, 59, 79, 89]: | |
if x > m: | |
d += 1 | |
return d | |
def simulate(i: int, hook: Callable[[int, int], None] | None = None) -> tuple[int, int]: | |
d_avg = 0 | |
r_avg = 0 | |
for n in range(i): | |
x = random.randint(0, 99) | |
d = demand(x) | |
d_avg = (n*d_avg + d) / (n + 1) | |
r_avg = (n*r_avg + d*4_300) / (n + 1) | |
if hook is not None: | |
hook(d_avg, r_avg) | |
return d_avg, r_avg | |
if __name__ == "__main__": | |
sim_hook = lambda d_avg, r_avg: print(f"{d_avg:.2f} ${r_avg:,.2f}") | |
simulate(15, sim_hook) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment