Consider you are standing at a street corner, in a city where the streets are laid out in a very regular grid pattern. At this point you randomly choose and intersection to turn on to (left, right, forward or backward - let’s say). You walk further to another intersection and make the same random choice. Rinse, lather, repeat. When you finally stop, your winding path is some direct distance away from your starting point. This is an example of a random walk. It’s a probabilistic simulation of certain statistical systems (like photons inside a star, or Brownian motion of molecules).
In n steps, how far do you expect to be from your starting point? Write a Python program to help answer this question.
(由留学作业帮www.homeworkhelp.cc整理编辑)
The requirements for this assignment are straightforward:
You will need to use function(s) from the Python random module.
Your main function will be used to ask for user input and loop, and perform m number of walks.
You will write a function called random_walk_2d that will perform a random walk of n steps. The function’s signature (its defined parameters, and return values) are to be designed.
Do not use the eval function.
The distance from your starting point (origin) is a unit-less measurement, don’t worry about giving the distance any real physical unit.
Code:
This programe helps to estimate the expected distance a man would move from a
starting point with a random walk.
import random
Returns a list of ints from 0-3 which represent the 4 directions
someone could walk in a grid pattern
def random_walk_2d(step_count):
path = []
Generate random ints between 0 and 3
for i in range(step_count):
path.append(random.randrange(0, 4))
return path
“”“This funciton takes a path which is a list of numbers 0-3 and
calculates the distance from it’s start point.
0 = up, 1 = right, 2 = down, 3 = left
“””
def distance_walked(path):
Distance Vars
x_distance = 0
y_distance = 0
Path eval
for i in range(len(path)):
if path[i] == 0:
y_distance += 1
elif path[i] == 1:
x_distance += 1
elif path[i] == 2:
y_distance -= 1
elif path[i] == 3:
x_distance -= 1
Distance Eval
distance = (x_distance ** 2 + y_distance ** 2)**(1 / 2)
return distance
def average_walk_distance(walk_count, step_count):
average_distance = 0
Calculate total
for i in range(walk_count):
average_distance += distance_walked(random_walk_2d(step_count))
Divide to get average
average_distance /= walk_count
return average_distance
def main():
print(“Simulation of two dimensional random walk”)
walks = eval(input("How many walks should I do? "))
steps = eval(input("How many steps should I take on each? "))
av_dist = average_walk_distance(walks, steps)
print(“Average distance from start: {0:0.2f}”.format(av_dist))
if name == ‘main’:
main()