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()

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)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.