So my current code effectively runs the "random walk" problem and then uses the pythagorean theorem to figure out actual distance in units walked but now I need to modify my program so that I can do a certain number of trials of said walk and then calculate the mean square distance. Not really looking for just an answer, I really also need an explanation so that I may be able to learn and recreate, I think I just need another while loop but I'm not sure where to put it.
import javax.swing.JOptionPane;
String a = JOptionPane.showInputDialog("Enter # of footsteps.");
int z = Integer.valueOf(a);
int x= 0; // starting x position
int y= 0; // starting y position
double r;
int counterZ = 0;
if (z < counterZ ){
System.out.println("Error");
}
while ( z > counterZ){
r=Math.random();
if (r<0.25){
x=x+1;
}
else if(r > .25 && r<0.50){
x=x-1;
}
else if(r > .5 && r<0.75){
y=y+1;
}
else{
y=y-1;
}
counterZ = counterZ + 1;
System.out.println("(" + x + "," + y + ")");
}
System.out.println("distance = " + round(sqrt((x*x)+(y*y))));
Correct me if i am wrong, My understanding is that you want to run the walk cycle a certain number of times and calculate the average distance walked on the sum of the distance of the cycles. If that is the case, then all you have to do is this,
the
randomWalk()
method should be like the following if you are calling it from the main method without creating an object for the classrandomWalk()
is residing in.you have also missed to call the methods
round()
andsqrt()
using there classMath
. I have correct them for you asMath.round()
andMath.sqrt()
. without the class name you will get a compiler error likeSymbol not found
. i also assume you have imported thejava.lang.Math
class into your program.