Member-only story

Modeling Random Walks in Python for Fun (and no profit)

Rhett Allain
10 min readJan 25, 2025

--

Photo: Rhett Allain. A fun little office toy with beads and random walks

I have this fun little office toy. It’s got a bunch of tiny balls that fall through some pegs. After bouncing around, the balls end up in different slots. Although an individual ball could end up in any of the slots — the middle slots end up with more balls. Even better, they form this nice “bell” curve that you see above. This is awesome.

In fact, this is an example of a one dimensional walk. Each time a ball hits a peg, it can go either to the left or to the right. You could reproduce this with a coin and a hallway. Take the coin and flip it. If it’s heads, move take one step to the right. If it’s tails, one step to the left. Keep doing this until you get bored — but yes, it’s a random walk (you know, because coin flips are random).

Let’s just go ahead and model this in python and then we can analyze it.

1D Random Walk

For all of this stuff, I’m going to use Web VPython. It’s not normal, plain python in that it doesn’t have all the same random number generators. That’s fine — it does have some super nice 3D graphics that we can use. It’s fun.

You can’t have a random walk without random numbers — so, let’s talk about random numbers in Web VPython. There’s really only one random function we can use, it’s random(). This returns a number…

--

--

Rhett Allain
Rhett Allain

Written by Rhett Allain

Physics faculty, science blogger of all things geek. Technical Consultant for CBS MacGyver and MythBusters. WIRED blogger.

Responses (10)