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)

Upvotes: 1

Views: 430

Answers (2)

Andy Wei
Andy Wei

Reputation: 618

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:

Upvotes: 3

Ahmed AEK
Ahmed AEK

Reputation: 17496

you should use random.choices, with the required weights.

rand = random.choices((1,2),weights=(0.4,0.6))  # 40% for 1 , and 60% for 2

Upvotes: 4

Related Questions