Created
December 14, 2018 02:27
-
-
Save k0mach1/2d294dbfd5169e7bcc991d848c90c4b2 to your computer and use it in GitHub Desktop.
Monte Calro Simulation Using python
This file contains 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 | |
## CONST | |
T = 60 | |
DT = 0.01 | |
LAMBDA = 2 | |
MU = 1 | |
N_MAX = 20 | |
## CLASS | |
class Agent: | |
def __init__(self, arrived_time): | |
self.arrived_time = arrived_time | |
self.finished_time = None | |
def set_finished_time(self, finished_time): | |
self.finished_time = finished_time | |
def get_waiting_time(self): | |
return self.finished_time - self.arrived_time | |
## UTIL | |
def average(arr): | |
return sum(arr) / len(arr) | |
## MAIN | |
not_arrived_agents = [] | |
queue_agents = [] | |
queue_length_list = [] | |
finished_agents = [] | |
# memo: agentの配列を作成 | |
last_arrived_time = 0 | |
while True: | |
time_gap = random.expovariate(LAMBDA) | |
last_arrived_time += time_gap | |
if last_arrived_time > T: | |
break | |
not_arrived_agents.append(Agent(last_arrived_time)) | |
# memo: 単位時間あたりのループを回す | |
loop = int(T / DT) | |
for n in range(loop): | |
t = round(n * DT, 2) | |
# memo: 到着を確認する | |
for a in not_arrived_agents: | |
if a.arrived_time <= t: | |
not_arrived_agents.pop(0) | |
if len(queue_agents) < N_MAX: | |
queue_agents.append(a) | |
else: | |
break | |
# memo: もし行列に誰もいなければループを抜ける | |
if not queue_agents: | |
continue | |
# memo: 処理されたかを確認する | |
processed_agent = queue_agents[0] | |
if processed_agent.finished_time is None: | |
processed_agent.set_finished_time(t + random.expovariate(MU)) | |
else: | |
if processed_agent.finished_time <= t: | |
finished_agents.append(processed_agent) | |
queue_agents.pop(0) | |
# if t % 10 == 0.0: | |
# averate_waiting_time = average(list(map(lambda a: a.get_waiting_time(), finished_agents))) | |
# # print(len(queue_agents)) | |
# print(averate_waiting_time) | |
queue_length_list.append(len(queue_agents)) | |
# memo: 行列の長さの平均を出力 | |
average_queue_length = average(queue_length_list) | |
print(average_queue_length) | |
# memo: 平均の待ち時間を出力 | |
averate_waiting_time = average(list(map(lambda a: a.get_waiting_time(), finished_agents))) | |
print(averate_waiting_time) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment