pythonstatisticscoin-flipping

Generate data from a coin flipping experiment


I have a coin and the coin has memory. i.e. the last flip impacts the probability of heads on this flip. How do I write code to generate data from this process? Specifically, from this process, I want to be able to generate n=1000 data points.

P(H | H_{-1}) != P(H | T_{-1}) #probability of heads given heads in last flip is not equal to probability of heads given tails in last flip
P(T | H_{-1}) != P(T | T_{-1}) #probability of tails given heads in last flip is not equal to probability of tails given tails in last flip

{-1} represents last flip

Assume P( H | H in last flip ) = 0.75
P( H | T in last flip ) = 0.30

Also, assume that the first flip of a coin has equal probability of landing a heads or tails.

Any help is greatly appreciated!!


Solution

  • Here is a skeleton that you can use for your experiment.

    import random
    
    def flip(last_flip):
        if last_flip == "H":
            #INSERT LOGIC FOR PROBABILITY IF PREVIOUS FLIP WAS HEADS
            heads_probability = 0.75
        elif last_flip == "T":
            #INSERT LOGIC FOR PROBABILITY IF PREVIOUS FLIP WAS TAILS
            heads_probability = 0.30
        else:
            heads_probability = 0.5
    
        tails_probability = 1-heads_probability
        flip = random.choices(["H", "T"], weights = (heads_probability, tails_probability))[0]
    
        return flip
    
    
    flips = []
    lastFlip = None
    for n in range(1000):
        newFlip = flip(lastFlip)
        flips.append(newFlip)
        lastFlip = newFlip
    

    This uses the random.choices function to select heads or tails with uneven probabilities. The flip function takes the previous flip as an input and calculates the new probability of the coin toss. You will need to fill this part in with the logic that you are using for your experiment (where the comments are).

    The main part of the code flips the coin and stores the result in an array. For the next trial, it uses the previous flip as input for the flip function discussed earlier.