Saturday, 9 October 2010

The Sun, a drunkard's walk and some Python...

I've been playing around with Python recently - the programming language that is, not the snake.  (Snakes are cool too though.)  One big difference with Python as opposed to PHP and Perl, the languages I normally use, is that Python is a little more geared towards graphical simulations rather than simply playing with a text input/output, especially with the pygame modules installed.  Coming from a physics background, an obvious starting point is to try simulating some simple particles and maybe some gravity.

I had a dig around and found this script by Niels Stender which does exactly that, in a fairly elegant way.  I find that tinkering with somebody else's code is a good way to get to grips with the syntax and style of a language.

Stender's code simply generates the particles and the relevant physics and starts them running, it's a good estimation of how particles behave in a gas, anything from the Earth's atmosphere to the interior of the Sun.  There's a classic fact that gets trotted out in many astrophysics lectures: it takes around a million years for a photon to get from the centre of the Sun to the surface...and photons travel at the speed of light.

Why so long?  Well the photons bounce around a lot, like the particles in this simulation.  The way they bounce around is random, like tossing a coin.  Toss a coin a thousand times and you'll get roughly 500 heads and 500 tails - the equivalent with our photon is that it stays pretty much where it started, at the centre.  The odds of it reaching the surface of the Sun are very small, it would be like tossing a coin a thousand times and getting a thousand heads...which is why it takes so long, the photon has to wait for something very unlikely to happen.  This process is known as a random walk, or slightly more poetically, a drunkard's walk.

Which is where my addition to the code comes in.  I fancied tracking one individual particle, no different to any of the others (except it's red, just to make it more visible) and recording the x coordinate.  Over time my code builds up a graph of the red particles position, which should, if the code and theory are correct, closely resemble a Bell curve, or a normal distribution pattern.  This shape pops up everywhere from population biology to the most fundamental quantum theories, it's a mathematical signature showing that something truly chaotic and random is happening:

Here's some video of my script running....

And now here's the same simulation, ten minutes later.  The graph in the bottom right is a reasonably good fit for the Bell curve, hooray!

You can have a tinker with the code yourself if you want - the source code is here. You'll need to install Python and pygame, both of which are free, if you don't have them already.

No comments:

Post a Comment