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.
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?