Search code examples
pythonnumpyrandom-walk

Storing intermediate values in a numpy array


I'm trying to simulate a 2-d random walk, with direction 0 < θ < 2π and T=1000 steps.

a=np.zeros((1000,1000))

def randwalk(x,y):
    theta=2*math.pi*rd.rand() 
    x+=math.cos(theta);          
    y+=math.sin(theta);          
    return (x,y)

How can I store all the intermediate coordinates in a? I was initially trying something of the form:

for i in range(1000):
    for j in range(1000):
        a[i,j] = randwalk(x,y)

But this doesn't seem to work at all.


Solution

  • The main obvious problem is that you want a 2D array of 1000 points, not a 1000x1000 array. For example, you say you want to take 1000 steps, but your nested loop takes 1,000,000.

    import numpy as np
    import matplotlib.pyplot as plt
    import random as rd
    import math
    
    a=np.zeros((1000,2), dtype=np.float)
    
    def randwalk(x,y):
        theta=2*math.pi*rd.random() 
        x+=math.cos(theta);          
        y+=math.sin(theta);          
        return (x,y)
    
    x, y = 0., 0.
    for i in range(1000):
        x, y = randwalk(x,y)
        a[i,:] = x, y
    
    plt.figure()
    plt.plot(a[:,0], a[:,1])
    plt.show()
    

    enter image description here