数学建模刚好有的有用到,于是手写代码实现一下

题目

设某仓库前有一卸货场,货车一般是夜间到达,白天卸货,每天只能卸货 2 车,若一天内到达数超过 2 车,那么就推迟到次日卸货。根据表 3 所示的数据,货车到 达数的概率分布(相对频率)平均为 1.5 车/天,求每天推迟卸货的平均车数。
蒙特卡洛模拟解决排队论 - 图1
解: 这是单服务台的排队系统,可验证到达车数不服从泊松分布,服务时间也不服从指数分布(这是定长服务时间)。随机模拟法首先要求事件能按历史的概率分布规律出现。模拟时产生的随机数与事件的对应关系如表4
蒙特卡洛模拟解决排队论 - 图2

解答

  1. import random
  2. prob=[0.23,0.3,0.3,0.1,0.05,0.02]
  3. def possess_prob(prob):
  4. temp=0
  5. new_prob=[]
  6. for i in prob:
  7. temp+=i
  8. new_prob.append(temp)
  9. print(new_prob)
  10. return new_prob
  11. def once(prob1,day):
  12. wait=0
  13. cur_wait=0
  14. for i in range(day):
  15. temp = random.random()
  16. index = 0
  17. for i in prob1:
  18. if temp < i:
  19. break
  20. index += 1
  21. cur_wait+=index
  22. if cur_wait>=2:
  23. cur_wait-=2
  24. else:
  25. cur_wait=0
  26. if cur_wait>0:
  27. wait+=cur_wait
  28. return cur_wait
  29. from Draw import Draw
  30. def run(times,day):
  31. print("----start----")
  32. prob1=possess_prob(prob)
  33. result=[]
  34. sum=0
  35. for i in range(times):
  36. temp=once(prob1,day)
  37. sum+=temp
  38. lens=len(result)+1
  39. result.append(sum/lens)
  40. Draw([result], ["test"], range(len(result)), "MonteCarlo Method")
  41. run(10000,100)

image.png