Skip to content

Instantly share code, notes, and snippets.

@EmilienDupont
Last active November 12, 2017 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmilienDupont/7cd47996390fe5b3b91481b823348bbc to your computer and use it in GitHub Desktop.
Save EmilienDupont/7cd47996390fe5b3b91481b823348bbc to your computer and use it in GitHub Desktop.
Random Walk in 3D

Random Walk in 3D

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 2D.

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();
var rand_num = Math.random();
if (rand_num < 1/3)
return {"x" : position.x + step, "y" : position.y, "z" : position.z};
else if (rand_num > 2/3)
return {"x" : position.x, "y" : position.y + step, "z" : position.z};
else
return {"x" : position.x, "y" : position.y, "z" : position.z + step};
}
function add_line(position, next_position, colour) {
svg.append("line")
.attr("x1", position.x + 0.5 * position.z)
.attr("y1", position.y - 0.5 * position.z)
.attr("x2", next_position.x + 0.5 * next_position.z)
.attr("y2", next_position.y - 0.5 * next_position.z)
.attr("stroke", colour)
.attr("stroke-width", 2)
.attr("stroke-opacity", sigmoid(0.01 * next_position.z)); // simulate depth
}
function sigmoid(z) {
return 1/(1 + Math.exp(-z));
}
var pos = {"x" : width/2, "y" : height/2, "z" : 0};
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