Skip to content

Generate random number in LaTeX

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.

\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 to "export" the random number ("NewRandom" in the example) into the text.

The function which actually 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:

\roman{SavedRandom}

or alphabetic characters:

\alph{SavedRandom}

Trackbacks

ads' corner on : Read number lines in a file

Show preview
Probably a rare needed feature, but i had to count the number lines in a text file - in LaTeX.Counting the line numbers is done by using a counter (what else, eh?) and readling the file line by line: \documentclass{book}\usepackage{ifthen}\newcounter{Fi Comments ()

Comments

Display comments as Linear | Threaded

No comments

Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications.
To leave a comment you must approve it via e-mail, which will be sent to your address after submission.
Form options