如何将含while循环的随机序列移动模拟代码封装为可复用函数
模拟逻辑的函数封装与批量运行实现
核心封装思路
把单次模拟的全流程收进独立的函数作用域,所有单轮使用的变量(序列、状态、记录值)都在函数内部初始化,不同轮次的模拟不会互相干扰;函数返回需要留存的模拟结果,外层只需要循环调用函数即可完成批量运行,不需要重复粘贴原有模拟代码。
修正后可直接复用的封装代码
说明:原代码存在一处逻辑bug——每个分支判断时会单独调用
random.random(),导致同一判断节点生成多个独立随机数,和原本“生成一个随机数和当前元素分数比较”的设计不符,封装时已修正为每次循环仅生成一次随机数用于判断。
import random import numpy as np import matplotlib.pyplot as plt def run_single_simulation( f_num=None, m_num=None, s_num=None, initial_pool=10, debug_print=False, random_seed=None ): # 单轮单独设置随机种子时生效,用于复现特定模拟场景 if random_seed is not None: random.seed(random_seed) # 按逻辑生成随机序列 f = f_num if f_num is not None else random.randint(0, 3) m = m_num if m_num is not None else random.randint(0, 3) s = s_num if s_num is not None else random.randint(0, 3) seq = [0.2] * s + [0.5] * m + [0.8] * f random.shuffle(seq) seq = [0.1] + seq seq = seq + [0.1] state = [0] * len(seq) record = [] count = 0 pool = initial_pool while count < len(seq) + 1: # 每次循环仅生成一次随机数,统一用于当前节点的判断 current_rand = random.random() if count == 0: # 序列起点:判断是否启动 if current_rand < seq[count]: if debug_print: print("START") print("random is less than", seq[count]) state[count] += 1 pool -= 1 if debug_print: print(state) record.append(state.copy()) count += 1 else: if debug_print: print("DOES NOT START") print("random is greater than", seq[count]) record.append(state.copy()) count += 0 elif 0 < count <= len(seq) - 1: if count == len(seq) - 1: # 序列终点:判断是否离开完成模拟 if current_rand < seq[count]: if debug_print: print("END") print("random is less than", seq[count-1]) state[count - 1] -= 1 pool += 1 if debug_print: print(state) record.append(state.copy()) count += 1 else: if debug_print: print("DOES NOT END") print("random greater than", seq[count-1]) record.append(state.copy()) count += 0 else: # 序列中间位置:判断是否移动到下一个元素 if current_rand < seq[count]: if debug_print: print("DOES MOVE") print("random is less than", seq[count]) state[count] += 1 state[count - 1] -= 1 if debug_print: print(state) record.append(state.copy()) count += 1 else: if debug_print: print("DOES NOT MOVE") print("random is greater than", seq[count]) record.append(state.copy()) count += 0 if debug_print: print("count is: ", count) # 返回单轮模拟的全部结果,方便后续统计 return { "generated_seq": seq, "state_record": record, "final_pool_value": pool, "final_state": state }
批量运行多次模拟的方法
外层写固定次数的循环,每次调用单模拟函数,把返回的结果统一存在列表中即可,不需要重复粘贴模拟逻辑。示例如下:
if __name__ == "__main__": simulation_times = 100 # 要跑的模拟次数,可自行修改 total_results = [] # 全局设置一次随机种子,保证整批模拟的结果可复现 random.seed(5) for round_idx in range(simulation_times): # debug_print设为False,避免批量运行时控制台被逐行打印刷屏 single_res = run_single_simulation(debug_print=False) total_results.append(single_res) print(f"第{round_idx+1}轮模拟完成,最终pool值:{single_res['final_pool_value']}")
新手使用注意事项
- 不要把
seq、state这类单轮使用的变量定义在函数外面:否则下一轮模拟启动时,上一轮的残留状态会污染结果 - 批量跑模拟时不要在函数内部固定随机种子:否则每一轮生成的序列、随机结果会完全相同,失去模拟的统计意义;需要复现特定场景时,再单独给单轮函数传
random_seed参数 - 可以自行扩展函数的入参:比如修改序列前后的0.1阈值、调整初始pool值,不需要改动函数内部的核心逻辑
- 批量运行时把
debug_print设为False,避免控制台被逐行打印的信息刷屏,需要调试某一轮模拟时再临时改成True
内容的提问来源于stack exchange,提问作者kevish
相关产品推荐
相关产品推荐

