A random walk is a stochastic process in which a particle moves one step at a time from state to state in a structured space. For us, the state space will be Z, the set of integers. The particle starts in an initial state S[0] ∈ Z. If, after i ≥ 0 steps, the particle is in state S[i], then in step i + 1, it moves to state S[i] + 1 with probability p and to state S[i] − 1 with probability q; it cannot stand still. Of course, p + q = 1. If S[0] = 5 and 0 < p < 1, then the sequence 5,4,3,4,3,2,3,2,3,4 is a possible sequence of states for the particle if it moves 9 times.
Write a program that will simulate a random walk for a given number of steps and that will compute certain statistics for the random walk. The parameters for a simulation come from standard input as a single line of parameters, consisting of (1) the initial state S[0]; (2) the value of p; and (3) the number of steps to simulate.
Note: I’m writing this in Java.
So far I have:
public static void main(String[] args) {
Random rand = new Random();
int iState = rand.nextInt();
int particle = iState;
double pValue = 0.60;
int numSteps = rand.nextInt() + 1;
int nSteps = 0;
if (numSteps>=0) {
System.out.println(particle);
while (nSteps<numSteps); {
if (rand.nextDouble() < pValue)
particle++;
else
particle--;
System.out.println(particle);
nSteps++;
}
}
Something seems to be going wrong though, so I’m stuck.
EDIT: Thanks guys, somehow I didn’t catch that semicolon.
//—————————————————————————————-
EDIT 2: Okay, so I have the code working correctly; however, in the end I am supposed to listed the maximum, minimum, and average values. Is this possible to do without creating a new variable for each iState value? My new code is
public static void main(String[] args) {
Random rand = new Random();
int iState = rand.nextInt();
double pValue = 0.60;
int numSteps = rand.nextInt(100) + 1;
int nSteps = 0;
if (numSteps>=0) {
System.out.println(iState);
while (nSteps<numSteps) {
if (rand.nextDouble() < pValue)
iState++;
else
iState--;
System.out.println(iState);
nSteps++;
I think your problem is that you need to delete the semicolon in the line
Also, you almost certainly don’t want to iterate for
rand.nextInt() + 1steps, sincerand.nextInt()could be negative. You might meanrand.nextInt(n)wherenis some upper bound, though, or you might just set it ton.UPDATE: If you need to track the minimum, maximum, and average values, you might do something like
Then, after each iteration, you say
and then at the end of the iteration, your minimum is in
min, your maximum is inmax, and your average is(double) total / numSteps.