You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查随机打印变量的概率并统计其出现频率?

统计随机元素的出现频率以验证选择概率

要测试三个变量各自的随机选择概率,核心思路是重复执行大量随机抽取操作,统计每个元素的出现次数,再计算其频率(频率会随着次数增加趋近于理论概率)。

下面是修改后的实现代码:

import random
from collections import defaultdict

# 定义三个变量的可选值
a_options = ("Word A1", "Word A2", "Word A3", "Word A4")
b_options = ("Word B1", "Word B2", "Word B3", "Word B4")
c_options = ("Word C1", "Word C2", "Word C3", "Word C4")

# 初始化统计字典
a_counts = defaultdict(int)
b_counts = defaultdict(int)
c_counts = defaultdict(int)

# 设置重复抽取的次数,次数越多结果越准确
total_trials = 100000

for _ in range(total_trials):
    a_selected = random.choice(a_options)
    b_selected = random.choice(b_options)
    c_selected = random.choice(c_options)
    
    # 累计计数
    a_counts[a_selected] += 1
    b_counts[b_selected] += 1
    c_counts[c_selected] += 1

# 计算并打印每个元素的频率
print("变量A的选择频率:")
for item, count in a_counts.items():
    print(f"{item}: {count / total_trials:.4f}")

print("\n变量B的选择频率:")
for item, count in b_counts.items():
    print(f"{item}: {count / total_trials:.4f}")

print("\n变量C的选择频率:")
for item, count in c_counts.items():
    print(f"{item}: {count / total_trials:.4f}")

关键说明:

  • 重复次数:这里设为100000次,次数越多,统计出的频率越接近理论上的25%(因为每个变量有4个可选值,均匀分布下每个值的概率是1/4)。
  • 统计方式:用defaultdict自动初始化计数为0,也可以用普通字典手动处理初始值。
  • 频率计算:用每个元素的出现次数除以总试验次数,得到的结果就是该元素的实际选择频率。

内容的提问来源于stack exchange,提问作者Evangelos Dellas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 21:15:02