Using Python, consider you are standing at a street corner, in a city where the
ID: 3815439 • Letter: U
Question
Using Python, consider you are standing at a street corner, in a city where the streets are laid out in a very regular grid pattern. At ths point you randomly choose and intersection to turn on to (left, right, forward or backward). You walk further to another intersection and make the same random choice. When you finally stop, your winding path is some direct distance away from your starting point. This is an example of a random walk.
In n steps, how far do you expect to be from your starting point? Write a program to help answer this question.
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.
Explanation / Answer
python 2.7 code:
import random
def walk(n):
x = 0.0
y = 0.0
for i in range(0,n):
c = random.randint(1,4)
if(c == 1):
x = x + 1
elif(c == 2):
x = x - 1
elif(c == 3):
y = y + 1
else:
y = y - 1
return (x**2 + y**2)**0.5
def main():
print "Enter the value of m"
m = int(raw_input().strip())
print "Enter the value of n"
n = int(raw_input().strip())
dist = 0.0
for i in range(0,m):
dist = dist + walk(n)
print "Expected distance after walking ", n, "Steps = ", float(dist)/float(m)
if __name__ == "__main__":
main()
Sample Output:
Enter the value of m
2
Enter the value of n
2
Expected distance after walking 2 Steps = 0.707106781187
C:UsersAkashDesktopchegg>python simple.py
Enter the value of m
1
Enter the value of n
1
Expected distance after walking 1 Steps = 1.0
C:UsersAkashDesktopchegg>python simple.py
Enter the value of m
1
Enter the value of n
1
Expected distance after walking 1 Steps = 1.0
C:UsersAkashDesktopchegg>python simple.py
Enter the value of m
100
Enter the value of n
5
Expected distance after walking 5 Steps = 2.17066668995
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.