0

I'm writing a two-dimensional random walk that takes command line arguments. It's supposed to estimate how long it takes the random walker to hit the boundary of a 2N-by-2N square centered at the starting point.

What I got so far is:

public class RandomWalk 
{
    public static void main(String[] args) 
    {
        int N = Integer.parseInt(args[0]);
        int reps = Integer.parseInt(args[1]);
        int x = 0;       
        int y = 0;       
        double r;
        int steps = 0;

        while (x*x + y*y <= N*N) {
            steps++;
            r = Math.random();

            if      (r <= 0.25) x++;
            else if (r <= 0.50) x--;
            else if (r <= 0.75) y++;
            else if (r <= 1.00) y--;
        }

        System.out.println(steps);
   }

}

Just want to check if you guys think im doing it wrong.

Tim
  • 35,413
  • 11
  • 95
  • 121
bangalo
  • 65
  • 3
  • 8
  • 2
    Are you having problems? This might be more appropriate for [Code Review](http://codereview.stackexchange.com/). – Beau Grantham Sep 06 '12 at 18:02
  • Yea you might be right. Dont know if im having any problems since im not nearly experienced enough on this to know. Just wanted to get a quick answer from someone that might know. Im asked to print it with N = 1000 and reps = 1000 and im getting 1528331 wich im guessing the steps the walker has to take. – bangalo Sep 06 '12 at 18:05
  • what is the second command line argument supposed to represent? – Eric Sep 06 '12 at 18:37
  • @Eric number of simulation runs? – brimborium Sep 06 '12 at 18:42

2 Answers2

3

Your program terminates only when the random walk reaches a treshold. Not the boundary of the area.

while (x*x + y*y <= N*N) {

An example: N = 100, x = 90, y = 90 ==> 90*90 + 90*90 = 16 200 > 10 000.

Switch it to:

while (x > -N && x < N && y > -N && y < N) {

This will be better. And your reps variable is newer used. Not even once, beside the setting it's value.What should be the purpose ot that?

Matzi
  • 13,770
  • 4
  • 33
  • 50
  • +1 Nice answer - to answer your question, I think he is supposed to take the average over the number of reps - so I think he's missing another loop in there. – jeff Sep 06 '12 at 22:28
1

Your boundary condition, x*x + y*y <= N*N describes a circle, not a square. Also, the phrasing "hit" implies the condition does not include the boundary (<).

You want Math.abs(x) < N && Math.abs(y) < N

Eric
  • 95,302
  • 53
  • 242
  • 374