import numpy as np from random import choices from statistics import mean class State(object): def __init__(self,state_id): self.transition_matrix = np.array([ [0, 0, 0, 0, 0, 0], [1, 0.2, 0, 0, 0, 0], [0, 0.8, 0.4, 0, 0, 0], [0, 0, 0.6, 0.6, 0, 0], [0, 0, 0, 0.4, 0.8, 0], [0, 0, 0, 0, 0.2, 1], ]) # 转移矩阵 self.state_id = state_id # 状态ID: 状态1的ID为0 def move(self): candidates = range(0, 6) # 转移目标 weights = self.transition_matrix[:, self.state_id] # 转移概率 result = choices(candidates, weights) # 产生随机转移结果 return State(result[0]) if __name__ == '__main__': e = 100000 # 试验次数 r = [] # 试验结果 for i in range(0,e): cur_state = State(0) # 初始状态: 状态1 count = 0 # 转移次数 while cur_state.state_id != 5: cur_state = cur_state.move() count += 1 r.append(count) # 记录结果 print(mean(r)) # 输出均值