Last active
March 10, 2023 02:04
-
-
Save minghao912/a5ce2ecde1e1f67d91558c254b59901b to your computer and use it in GitHub Desktop.
C&EE 185/285 HW3 Q1: Code for Monte Carlo Simulation
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
import random | |
# Values given in table 3 | |
# In the format [car, transit, taxi] | |
given_mode_choice_probabilities = [ | |
[0.75, 0.23, 0.02], | |
[0.93, 0.06, 0.01], | |
[0.21, 0.41, 0.38], | |
[0.09, 0.24, 0.67], | |
[0.66, 0.13, 0.21], | |
[0.21, 0.35, 0.44], | |
[0.43, 0.36, 0.21], | |
[0.41, 0.36, 0.23], | |
[0.59, 0.10, 0.31], | |
[0.39, 0.04, 0.57] | |
] | |
for person_id, person_probs in enumerate(given_mode_choice_probabilities): | |
# Create cumulative probabilities | |
cum_prob = [] | |
for i, prob in enumerate(person_probs): | |
cum_prob.extend([i] * int(prob * 100)) | |
# Generate random number from U[0, 1] | |
# In our case, we normalize 1 -> 100 because ints are easier to work with, so we draw from U[0, 100] | |
r = random.randint(0, 100) | |
# Pick from alternatives | |
chosen_alternative = cum_prob[r] | |
# Print result | |
alternatives = ['car', 'transit', 'taxi'] | |
print(f"ID {person_id + 1}: {alternatives[chosen_alternative]}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment