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.
\def\coinflip#1{%
        \ifnum#1>\pdfuniformdeviate1000
                H%
        \else
                T%
        \fi
}
\tt
\parindent=0pt
\raggedright
\newcount\n \n=0
\newcount\heads \heads=0
\newcount\tails \tails=0
\loop\ifnum\n<1000
        \if\coinflip{327}H%
                \advance\heads by 1
                H
        \else
                \advance\tails by 1
                T
        \fi
        \advance\n by 1
\repeat

\vskip\baselineskip
\rm
$p=0.327$\par
Heads: \number\heads\par
Tails: \number\tails
\bye
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.

3 comments:

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

    ReplyDelete
  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.

    ReplyDelete
  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.

    ReplyDelete