Pseudocode
From Statistical Mechanics: Algorithms and Computations
Pseudocode is a way of defining computer programs without adhering to any particular language. No formal standard exists for pseudocode, so it means different things to different authors. Pseudocode in Statistical Mechanics: Algorithms and Computations resembles the python programming language. Like python, it is optimized for clarity while minimizing the number of lines written: No program is longer than half a printed page.
As an example, we may consider the first program in SMAC-book, the algorithm "Direct pi", one of the featured programs in chapter 1. So this is SMAC-book pseudocode for randomly throwing pebbles into a square of length 2, and checking how many of them fall inside an inscribed circle:
In most traditional computer languages (C, Fortran, C++), we would declare Nhits as an integer variable, and x and y as reals. We would also choose a value for the integer constant N, for example N = 4000 and increment the loop variable i more explicitly. The loop itself would not be described by a brace. In pseudocode, all these quite trivial points are left aside and, in fact, the variable N is initialized in the caption of the program! It is easy to translate "Direct pi" into a running computer program, in Python, Mathematica, Fortran, C, C++, matlab, or even in TI-Basic, the language used in many pocket calculators (further help is available). Later in the book, programs become more complicated, but not necessarily longer than the algorithm "Direct pi".
For comparison, we show here how this same program would be written in Python, a modern object-oriented language.
from random import uniform as ran
def direct_pi(N):
N_hits=0
for i in range(N):
x,y=ran(-1.,1.),ran(-1.,1.)
if x**2 + y**2 < 1: N_hits += 1
return N_hits
for k in range(10):
print k, direct_pi(10000)
Many Python programs of algorithms in Statistical Mechanics: Algorithms and Computations can be found here.
A favorite short and sweet algorithm is "Direct surface". It uses Gaussian random numbers to randomly sample points on the surface of a circle, a sphere, or, more generally, a d-dimensional hypersphere. With its dozen lines to program it hinges on nothing less than the famous Maxwell distribution of particles in a liquid or gas, a cornerstones of Statistical Mechanics.
