Generate random number in LaTeX

Posted by ads on Saturday, 2010-02-27
Posted in [Tex]

It is possible to generate random numbers in a TeX document. For a gimmick I wanted a random line from a text file in my slides. The first step was to find a random number.

A random number generator is provided by the package lcg. The generator can be initialized with a given positive value. The same positive seed results in the same random numbers. A seed of -1 initializes the generator with a more or less random value, based on the current time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
\documentclass{book}

\usepackage{lcg}

\newcounter{SavedRandom}
\newcommand{\NewRandom}

\newcommand{\GenerateRandumNumber}[2]
{
 \setcounter{SavedRandom}{0}
 \reinitrand[first=1, last=#1, counter=FileRandom, seed=-1, quiet=y]

 \rand
 \setcounter{SavedRandom}{\value{FileRandom}}
 \renewcommand{#2}{\arabic{SavedRandom}}
}

\begin{document}

\GenerateRandumNumber{15}{\NewRandom}

Random number: \NewRandom

\end{document}

In addition it needs a counter to store the random value (SavedRandom in my example) and a command to export the random number (NewRandom in the example) into the text.

The function which initializes the random generator accepts two parameters: the highest possible random number (the min value is set to 1 in my example) and the command to store the generated random number (NewRandom). The number is exported as arabian number, it’s also possible to use roman numerals:

1
\roman{SavedRandom}

or alphabetic characters:

1
\alph{SavedRandom}

Categories: [Tex]

Share: