想要实现一个功能:不同事件发生的基础概率不同,根据基础概率来随机生成选项。
比如,北京的秋天有四种状态,并分别对应一个基础概率,然后随机生成某一天的天气情况。
weatherlist = ['Sunny', 'Cloudy', 'Windy', 'Rainy']
probaslist = [0.30, 0.35, 0.25, 0.1]
实现脚本如下:
import random def generate_weather(weather_list, probabilities_list): if not (0.99999 < sum(probabilities_list) < 1.00001):
raise ValueError("The probabilities are not normalized!")
if len(weather_list) != len(probabilities_list):
raise ValueError("The length of two input lists are not match!") random_normalized_num = random.random() # random() -> x in the interval [0, 1).
accumulated_probability = 0.0
for item in zip(weather_list, probabilities_list):
accumulated_probability += item[1]
if random_normalized_num < accumulated_probability:
return item[0]
测试运行情况:
weatherlist = ['Sunny', 'Cloudy', 'Windy', 'Rainy']
probaslist = [0.30, 0.35, 0.25, 0.1] output_dict = {}
for x in weatherlist:
output_dict.update({x: 0}) n = 10000
for i in range(n):
weather = generate_weather(weatherlist, probaslist)
output_dict[weather] += 1 percentage_dict = {key: output_dict[key]/n for key in output_dict}
print(output_dict)
print(percentage_dict)
得到的结果为:
{'Sunny': 3033, 'Cloudy': 3466, 'Windy': 2484, 'Rainy': 1017}
{'Sunny': 0.3033, 'Cloudy': 0.3466, 'Windy': 0.2484, 'Rainy': 0.1017}
模拟生成10000次天气情况,将各种天气情况的频率与初始设置的基础概率比较,发现结果很吻合。
巨人的肩膀: