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

如何最小修改现有Python代码实现正面概率3/4的偏置硬币模拟?

偏置硬币模拟最小修改方案

你只需要修改两处现有代码即可实现需求,其余逻辑完全不需要调整:

  • 修改coin_surface_dictionary的权重配置,将正面概率调整为3/4
  • 替换get_coin_surface()函数中的等概率抽样方法,改为带权重的随机抽样,直接复用已经定义的权重字典即可

修改后完整代码:

import random

SIMULATION_COUNT = 9999999
# 第一处修改:调整硬币正反面概率
coin_surface_dictionary = {'H':0.75, 'T': 0.25}

def get_coin_surface():
    # 第二处修改:替换为带权重的随机选择,返回值格式和原有逻辑完全一致
    return random.choices(list(coin_surface_dictionary.keys()), weights=list(coin_surface_dictionary.values()))[0]

def get_three_coin_surface():
    list_vector = []
    list_vector.append(get_coin_surface())
    list_vector.append(get_coin_surface())
    list_vector.append(get_coin_surface())
    return list_vector

if __name__ == "__main__":
    one_head_count_int = 0
    total_head_count = 0
    for ch in range(1, SIMULATION_COUNT):
        coin_surface_vector = get_three_coin_surface()
        head_count_int = coin_surface_vector.count("H")
        total_head_count += head_count_int
        if head_count_int == 1:
            one_head_count_int = one_head_count_int + 1
    probability = one_head_count_int / SIMULATION_COUNT
    ex = total_head_count / SIMULATION_COUNT
    print(f"P(X=1) 模拟值:{probability}")
    print(f"EX 模拟值:{ex}")
    # 理论值参考:P(X=1) = C(3,1)*(3/4)*(1/4)^2 = 9/64 ≈ 0.140625,EX = 3*(3/4) = 2.25

补充说明

你原有代码里已经提前定义了权重字典,本次修改没有新增任何额外变量,仅调整了两处逻辑,和原有代码的兼容性最高,改动量最小。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 00:12:02