pythonnumpyrandomcoin-flipping

Implementing a bias in coin toss simulation


I want to simulate a biased coin being flipped 2048 times and record the results from each attempt, along with the total count of each coin. My current code is fully functional and is able to simulate a fair coin, but I'm unsure about how to implement a bias of 0.25 within my current code. What can I do to add this particular bias?

def heads_tails(number_of_flips):
    tails_count = 0
    heads_count = 0
    for i in range(number_of_flips):
        rand = random.randint(1,2)
        if rand == 1:
            tails_count += 1
            print(tails_count, 'tails')
        else:
            heads_count += 1
            print(heads_count, 'heads')
    print('Total Heads: ', heads_count)
    print('Total Tails: ', tails_count)

heads_tails(2048)

Solution

  • You can modify this part of your code

    rand = random.randint(1,2)
        if rand == 1:
    

    to

    rand = random.random() # randoms a value between 0.0 and 1.0
        if rand < 0.25: