这是描述程序终止的模拟的一部分。有人可以帮助我理解这部分模拟工作我完全失去了。代码如下:
while time_elapsed < end_time :
event=birth () +death () +infection()
choice=random.random()*event
choice -= birth()
time_elapsed += random.expovariate(event)
if choice < 0 :
do_birth()
continue
choice -= death()
if choice < 0:
do_death()
continue
答案 0 :(得分:0)
我重新安排了它,希望能让事情变得更加明显:
# at each time-step until sim ends
while time_elapsed < end_time :
#
# decide which random event will occur
#
# cumulative probability = (chance of birth) + (chance of death) + (chance of infection)
event = birth() + death() + infection()
# choose a value in [0..cum_prob)
choice = random.random() * event
# interpret the value:
# if 0 <= value < (chance of birth) => birth
# if (chance of birth) <= value < (chance of birth) + (chance of death) => death
# if (chance of birth) + (chance of death) <= value < (chance of birth) + (chance of death) + (chance of infection) => infection
choice -= birth()
if choice < 0 :
do_birth()
continue
choice -= death()
if choice < 0:
do_death()
continue
# "what to do in case of infection" is missing;
# I assume you chopped it off while cut-and-pasting.
# forward to next time-step;
# this uses an exponential step-size, giving
# a normal distribution of event intervals
# rather than a uniform step size
time_elapsed += random.expovariate(event)
我会用不同的方式写出来:
while now < stop_at:
birth_point = prob_birth()
death_point = birth_point + prob_death()
all_events = death_point + prob_infection()
event = random.random() * all_events
if event < birth_point:
do_birth()
elif event < death_point:
do_death()
else:
do_infection()
now += random.expovariate(all_events)