Skip to content

Instantly share code, notes, and snippets.

@mikeskaug
Last active May 20, 2017 04:05
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 mikeskaug/198cb8353721262cc3bb2647307a74d4 to your computer and use it in GitHub Desktop.
Save mikeskaug/198cb8353721262cc3bb2647307a74d4 to your computer and use it in GitHub Desktop.
Random Walk

Simulation of a simple two dimensional Gaussian random walk. Random walks are used to model and understand many physical phenomena such as the movement of molecules through our bodies, the spread of contaminants underground and the fluctuation of stock prices.

<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="index.js"></script>
</body>
const width = window.innerWidth;
const height = window.innerHeight;
const originX = width / 2;
const originY = height / 2;
const vertices = [{x: 0, y: 0}];
const STEP_SIGMA = 5;
const MAX_STEPS = 5000;
const line = d3.line()
.x(d => { return originX + d.x })
.y(d => { return originY + d.y });
const svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
function withinBounds (vertices) {
let lastPoint = vertices[vertices.length - 1];
return (originX + lastPoint.x) > 0 &&
(originX + lastPoint.x) < width &&
(originY + lastPoint.y) > 0 &&
(originY + lastPoint.y) < height;
}
svg.append("path");
const path = svg.selectAll("path").data(vertices);
const marker = svg.selectAll('circle')
.data(vertices)
.enter().append('circle')
.attr('r', 5)
.attr('cx', d => { return originX + d.x })
.attr('cy', d => { return originY + d.y });
const timer = d3.timer(elapsed => {
if (withinBounds(vertices) && vertices.length < MAX_STEPS) {
let last = vertices[vertices.length-1];
let xPos = last.x;
let yPos = last.y;
xPos += d3.randomNormal(0, STEP_SIGMA)();
yPos += d3.randomNormal(0, STEP_SIGMA)();
vertices.push({x: xPos, y: yPos});
path.attr("d", d => line(vertices));
marker
.attr('cx', d => { return originX + vertices[vertices.length-1].x })
.attr('cy', d => { return originY + vertices[vertices.length-1].y });
} else {
timer.stop();
}
});
body {
margin: 0;
text-align: center;
font-family: sans-serif;
font-size: 14px;
}
path {
stroke: rgb(70, 70, 70);
stroke-linejoin: round;
stroke-width: 2px;
fill: none;
}
circle {
fill: black;
stroke: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment