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

How can I modify the following program to simulate a biased coin?

问题如下:

Simulate flipping three fair coins and counting the number X of heads.

  1. Use your simulation to estimate P(X = 1) and EX. Compare the estimates with the true values, derived from theoretical computations.
  2. Modify the above to allow for a biased coin where 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', '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','H','H','T'])