2

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.

  • why is it a 2d array? – njzk2 Oct 14 '14 at 17:04
  • Your numpy array is the wrong size. You want `a=np.zeros((1000,2))`, ie, 1000 2D points. Also, please post a minimal and complete piece of code, that is, something we can cut and paste and run. For example, in the line `a[i,j]=randwalk(x,y)`, what are `x` and `y`? – tom10 Oct 14 '14 at 17:04

3 Answers3

1

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

tom10
  • 67,082
  • 10
  • 127
  • 137
0

You probably want something like

T = 1000
a = [(0,0)] * T

for i in range(1, len(a)):
    a[i] = randwalk(*a[i - 1])

No need for numpy here.

njzk2
  • 38,969
  • 7
  • 69
  • 107
0

You've got a type error. randwalk is returning a 2-tuple, and you're trying to set an array element where a float is expected.

First of all, you don't want a 1000 by 1000 array. This would give a million data points, and you only need 2000. I think what you want is something like this:

xs = np.zeros((1000))
ys = np.zeros((1000))
x = 0
y = 0
for i in range(1000):
    xs[i], ys[i] = randwalk()

Also, should change the definition of randwalk to take no parameters, and to make x and y global variables:

def randwalk():
    global x, y

As you have it, you're modifying the values of the parameters, but they aren't accumulated from call to call.

saulspatz
  • 5,011
  • 5
  • 36
  • 47