import itertools from collections import Counterimport math # 用列表类型保存一骰子(色子)的可能结果 dice =1, 2, 3, 4, 5, 6] # 表示并两只骰子的可能数组合 combinations = list(itertools.product(dice, repeat=2)) # 将两只骰子的点数之和作为随机事件,计算出每种组合的频数 counts = Counter([sum(comb) for comb in combinations]) # 计算每种组合的频率(概率) probs = {k: v/len(combinations) for k, v in counts.items()} # 计算熵 entropy = -sum([p * math.log2(p) for p in probs.values()]) print("骰子点数之和的概率分布熵为:", entropy)修改代码
时间: 2023-12-22 12:06:40 浏览: 66
import itertools
from collections import Counter
import math
dice = [1, 2, 3, 4, 5, 6]
combinations = list(itertools.product(dice, repeat=2))
counts = Counter([sum(comb) for comb in combinations])
probs = {k: v/len(combinations) for k, v in counts.items()}
entropy = -sum([p * math.log2(p) for p in probs.values() if p > 0]) # 加入判断避免出现log2(0)的错误
print("骰子点数之和的概率分布熵为:", entropy)
阅读全文