微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何修改以下程序来模拟有偏差的硬币?

如何解决如何修改以下程序来模拟有偏差的硬币?

问题如下:

模拟掷三个公平的硬币并计算正面的数量 X。

  1. 使用您的模拟来估计 P(X = 1) 和 EX。将估计值与根据理论计算得出的真实值进行比较。
  2. 修改上述内容以允许 P(heads)=3/4 的有偏硬币。

我已经能够模拟如下无偏硬币:

import random


SIMULATION_COUNT = 9999999

coin_surface_dictionary = {'H':0.5,'T': 0.5}

def get_coin_surface():
    return random.choice(['H','T'])

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
    for ch in range(1,SIMULATION_COUNT):
        coin_surface_vector = get_three_coin_surface()
        head_count_int = coin_surface_vector.count("H")
        if head_count_int == 1:
            one_head_count_int = one_head_count_int + 1
        # END if
    # END for loop
    probability = one_head_count_int / SIMULATION_COUNT
    print(probability)

如何通过最少修改此源代码来模拟有偏见的硬币?

解决方法

要么保留您的 random.choice 但在 ('H','H','T') 之间进行选择,或者只是要求 [0,1] 之间的浮点数并与 0.75 进行比较。如果更高,则为反面,否则为正面。

一种考虑概率和的使用字典的稳健方法:

from random import random

SIDE_PROBABILITIES = {'H': 0.75,'T': 0.25}


def prob_of(side: str) -> float:
    return SIDE_PROBABILITIES[side] / sum(SIDE_PROBABILITIES.values())


def get_coin_surface() -> str:
    return 'H' if random() < prob_of('H') else 'T'


for _ in range(10):
    print(get_coin_surface())
,

好吧,如果您希望正面有 3/4 的机会,而不是简单地将您的 get_coin_surface() 函数修改为:

def get_coin_surface():
    return random.choice(['H','T'])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。