import itertools from collections import Counter # 保存一只骰子的可能结果 dice = [1, 2, 3, 4, 5, 6] # 表示并保存两只骰子的可能点数组合 combinations = list(itertools.product(dice, repeat=2)) # 将两只骰子的点数之和作为随机事件,计算出每种组合的数量(频数) freq = Counter([sum(c) for c in combinations]) # 计算每种组合的频率(概率) total = sum(freq.values()) prob = {k: v/total for k, v in freq.items()} # 计算概率分布的熵 entropy = -sum([p * math.log2(p) for p in prob.values()]) print("熵为:", entropy) 修改此代码
时间: 2023-12-23 10:01:54 浏览: 124
import itertools
from collections import Counter
import math # 添加math库
# 保存一只骰子的可能结果
dice = [1, 2, 3, 4, 5, 6]
# 表示并保存两只骰子的可能点数组合
combinations = list(itertools.product(dice, repeat=2))
# 将两只骰子的点数之和作为随机事件,计算出每种组合的数量(频数)
freq = Counter([sum(c) for c in combinations])
# 计算每种组合的频率(概率)
total = sum(freq.values())
prob = {k: v/total for k, v in freq.items()}
# 计算概率分布的熵
entropy = -sum([p * math.log2(p) for p in prob.values() if p != 0]) # 避免出现概率为0时导致计算错误
print("熵为:", entropy)
阅读全文