zoukankan      html  css  js  c++  java
  • Python3根据基础概率随机生成选项

    想要实现一个功能:不同事件发生的基础概率不同,根据基础概率来随机生成选项。

    比如,北京的秋天有四种状态,并分别对应一个基础概率,然后随机生成某一天的天气情况。

    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次天气情况,将各种天气情况的频率与初始设置的基础概率比较,发现结果很吻合。

    巨人的肩膀:

    https://www.cnblogs.com/zmlctt/p/4315783.html

  • 相关阅读:
    6-Python爬虫-分布式爬虫/Redis
    ES 查询时 排序报错(fielddata is disabled on text fileds by default ... )解决方法
    Intellij Idea webstorm 激活
    Intellij Idea 配置jdk
    java 获取(格式化)日期格式
    js 跳转 XSS漏洞 预防
    CSS去掉背景颜色
    js对象无法当成参数传递 解决方法
    Elasticsearch java api
    java多条件查询SQL语句拼接的小技巧
  • 原文地址:https://www.cnblogs.com/zhangwei22/p/9894954.html
Copyright © 2011-2022 走看看