Reputation: 7
I am having trouble producing a simple random walk path similar to what I use in my spreadsheets. How do I write the code so that each step is added to the previous step in order to keep a "running total" that would show distance from zero? Starting at zero, plus one step, plus one step, minus one step would equal +1 (0+1+1-1). Using random selection of course.
Also, is there a way to plot a chart of this with Python3.4?
import random
a = 0
trials = input('Trails : ')
while a < int(trials):
a = a + 1 # Simple step counter
x = random.randint(-1,1) # Step direction (-1, 0, +1)
print(a,x) # Prints numbered list of steps and direction
Upvotes: 0
Views: 995
Reputation: 3483
The position as a function of number of random steps made can be calculated with np.cumsum(np.random.randint(-1,2,10))
. You can plot it as a function of number of steps with
import numpy as np
import matplotlib.pyplot as plt
increment = np.random.randint(-1,2,10)
position = np.cumsum(increment)
plt.plot(np.arange(1, position.shape[0]+1), position)
plt.show()
Upvotes: 0
Reputation: 9704
This should do it (i.e. keep a running total) - as for plotting - you might need to keep the total for each step in a list and use another library - such as matplotlib, to plot the results.
import random
a = 0
total = 0 # Keep track of the total
trials = input('Trails : ')
while a < int(trials):
a = a + 1 # Simple step counter
x = random.randint(-1,1) # Step direction (-1, 0, +1)
total += x # Add this step to the total
print(a,x, total) # Prints numbered list of steps and direction
Upvotes: 2