-1

The problem is as follows:

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.

I have been able to simulate an unbiased coin as follows:

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)

How can I simulate a biased coin by minimally modifying this source code?

user366312
  • 16,949
  • 65
  • 235
  • 452

1 Answers1

2

Either retain your random.choice but choose between ('H', 'H', 'H', 'T'), or just ask for a float between [0, 1] and compare to 0.75. If higher, then it's tails, otherwise heads.

A somewhat-robust method of using your dictionary that takes into account the probability sum:

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())
Reinderien
  • 11,755
  • 5
  • 49
  • 77
  • Can I make use of the dictionary as I attempted? – user366312 Jul 20 '21 at 20:55
  • Yes-ish. Note that for the program to have a reasonable guarantee of correctness whatever the values in the dictionary, you need to pay attention to their sum and not just one of the probabilities. – Reinderien Jul 20 '21 at 21:03