I'm wondering why if I increase the number of step in a set of simulation of a random walk on a grid the distance from the origin is higher.
If I can move on the grid in 4 directions, there are 0.5 chance of getting closer to origin and 0.5 of getting farther.
This is a simple javascript example (well, here maybe I made some other errors because the points ends always with a negative x and a positive y, or maybe I just cannot rely on javascript random function in this case)
var steps = 100; //number of steps for each simulation (initially)
var simulations = 100; //number of total simulation
var points = Array.from({length:simulations}, () => ({x:0,y:0})); // init the array of points from the origin
//the 4 possible moves
var moves = [{x:0,y:1},{x:1,y:0},{x:0,y:-1},{x:-1,y:0}];
//ranom util function
var random = (max) => parseInt(Math.random() * max)
for (var s=0;s < simulations;s++) {
//note the steps are increasing: 100,200,300,...,1000
for (var i=1;i <= steps * s;i++) {
let move = moves[random(4)];
//console.log(move)
points[s].x += move.x
points[s].y += move.y
//console.log(s, move)
}
console.log(`simulation n.${s} total steps: ${steps*s}`, points[s].x, points[s].y, `distance: ${Math.abs(points[s].x) + Math.abs(points[s].y)}` )
}
EDIT: thanks to @GASSA I fixed my code, but watching the results I'm still in doubt: the distance actually is not increased (see the graph below). Not sure what's the problem..
var moves = [{x:0,y:1},{x:0,y:1},{x:0,y:-1},{x:-1,y:0}];
is buggy: one of{x:0,y:1}
should be{x:1,y:0}
instead. $\endgroup$ – Gassa Aug 5 '18 at 22:51