pythonjupyter-notebooksimulationrandom-walkcoin-flipping

Random walk simulation based on the flipping of a biased coin 100 times


I'm starting in Python. I'm trying to make a simulation of a random walk in a straight line (north and south) based on flipping a biased coin 100 times with 0.3 chance of getting tails and 0.7 chance of getting heads assuming that the values from the starting point to the south are negative and from the starting point to the north are positive.

I tried two different things but they don't work properly.

import random
def prob(p):
return random.random()<p
def random_walk(n):
heads=0
tails=0
t=0
for i in range(n):
    if prob(0.3):
        heads += 1
        t=t-1
    if prob (0.7):
        tails += 1
        t=t+1
print (heads, "heads")
print (tails, "tails")
print (t)
return t

heads=0
tails=0
t=0
for i in range(0,100):
    if prob(0.3):
        heads += 1
        t=t-1
    if prob(0.7):
        tails += 1
        t=t+1
print (heads, "heads")
print (tails, "tails")
print (t)

Solution

  • The issue here is with your calls to the prob function. Since you call the function twice within each iteration of your for i in range(n) loop, you end up with two different RNs.

    Also, if random.random() returns, say, 0.1 and 0.2, then both if blocks associated with if prob(0.3): and if prob(0.7): will execute in the same simulation loop.

    You need to call random.random() a single time per execution loop, and make both if statements mutually exclusive - changing it to a if/else block, for example.

    Here's a way to fix these issues:

    for i in range(n):
        coin_has_flipped_tails = prob(0.3)
        if coin_has_flipped_tails:
            tails += 1
            t += 1
        else:  # this implies that the coin has flipped head
            heads += 1
            t -= 1