0

I need the function to be able to walk in all four directions with equal probabbility and return the distance away from the starting point. The function below only takes steps forwards and backwards?

def main():
    numWalks, numSteps = getInputs()
    averageSteps = takeWalks(numWalks, numSteps)
    printExpectedDistance(averageSteps)

def getInputs():
    numWalks = input("How many random walks to take? ")
    numSteps = input("How many steps for each walk? ")
    return numWalks, numSteps

def takeWalks(numWalks, numSteps):
    totalSteps = 0
    for walk in range(numWalks):
        stepsAway = takeAWalk(numSteps)
        totalSteps = totalSteps + stepsAway
    return float(totalSteps) / numWalks

def printExpectedDistance(averageSteps):
    print "The expected number of steps away from the "
    print "start point is", averageSteps

def takeAWalk(numSteps):
    from random import random
    stepsForwardOfStart = 0
    for step in range(numSteps):
        if random() < 0.5:
            stepsForwardOfStart = stepsForwardOfStart - 1
    else:
        stepsForwardOfStart = stepsForwardOfStart + 1
        return abs(stepsForwardOfStart)

main()
2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by thecheesewheel
1

one way to do this would be to use a coordinate system to store the current position (ie x,y) and then calculate the distance from that position to the starting position using trigonometry. your random direction routine would need to then handle 4 states: up (y + 1), down (y - 1), left (x - 1) and right (x + 1)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.