Skip to content

Instantly share code, notes, and snippets.

@EmilienDupont
Last active February 10, 2021 23:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EmilienDupont/4da87ba851221f4ce150d798196da421 to your computer and use it in GitHub Desktop.
Save EmilienDupont/4da87ba851221f4ce150d798196da421 to your computer and use it in GitHub Desktop.
Random Walk in 2D

Random Walk in 2D

Visualization to illustrate the crazy fact that a random walk on the integer lattice in dimension d <= 2 will return to its starting point with probability 1 whereas a random walk in dimension d >= 3 has a finite probability of never returning. Or in other words:

"A drunk man will find his way home, but a drunk bird may get lost forever." - Shizuo Kakutani

Click here for a random walk in 3D.

For a cool proof of this theorem using Fourier analysis check e.g. the Fourier Transform and its Applications.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
background: #222;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
step_size = 3;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height);
function get_sign() {
return Math.random() > .5 ? 1 : -1;
}
function take_step(position) {
var step = step_size * get_sign();
if (Math.random() > .5)
return {"x" : position.x + step, "y" : position.y};
return {"x" : position.x, "y" : position.y + step};
}
function add_line(position, next_position, colour) {
svg.append("line")
.attr("x1", position.x)
.attr("y1", position.y)
.attr("x2", next_position.x)
.attr("y2", next_position.y)
.attr("stroke", colour)
.attr("stroke-width", 2);
}
var pos = {"x" : width/2, "y" : height/2};
var next_pos;
var counter = 0;
d3.timer(function() {
next_pos = take_step(pos);
add_line(pos, next_pos, d3.hsl((counter = (counter + 1) % 360), 1, .5));
pos = next_pos;
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment