Saturday, March 19, 2011

Random numbers in TeX

Recent versions of pdfTeX contain primitives for generating random integers.
  • \pdfuniformdeviate num generates a uniformly distributed random integer in the range [0, num).
  • \pdfnormaldeviate generates a normally distributed random integer with mean 0 and “a unit of 65536”. (I've never seen unit used that way, so I'm not sure exactly what the manual means.)

These are both expandable and can be used if you need random numbers for some reason. Here's one toy example that generates coinflips with a biased coin.
\newcount\n \n=0
\newcount\heads \heads=0
\newcount\tails \tails=0
                \advance\heads by 1
                \advance\tails by 1
        \advance\n by 1

Heads: \number\heads\par
Tails: \number\tails
This generates 1000 coin flips with a bias of p = 0.327. It prints the results of each coin flip as well as counting the number of heads and tails.


  1. By “unit” in the context, surely they mean standard deviation? After a few test runs of \pdfnormaldeviate that seems likely.

  2. It is probably either standard deviation or variance. It'd be easy enough to check by generating 1000 numbers and actually computing the variance.

  3. I do not use PDF, I just use only standard TeX. I am not sure why I would need random numbers in TeX, but I could make up some macro to do pseudo random numbers if I needed to.