# Random numbers and if statements

I want to produce a random number and with this check an if statement. But it does not work. I tried the following:

\documentclass{minimal}
\usepackage[first=0, last=1]{lcg}
\newcommand{\random}{\rand\arabic{rand}}
\begin{document}

\def\var{\random}

\ifnum\var=1
We have a one.
\fi

\ifnum\var=0
We have a zero.
\fi

\end{document}


I thought that the reason might be that the variable \var is not of the same type as 0 or 1. Can anybody help?

\rand is not “expandable”. It is an instruction for setting a counter, namely rand to some value.

Thus \ifnum doesn't find just a number, but a set of instructions to produce one.

You can avoid the issue by using an indirect method:

\documentclass{article}
\usepackage[first=0, last=1]{lcg}

\newcommand{\newrandomvar}[1]{%
\newcommand{#1}{}% be sure the name is not taken
\rand
\edef#1{\arabic{rand}}% note \edef to end up with the actual value
}

\begin{document}

\newrandomvar{\var}

\ifnum\var=1
We have a one.
\fi

\ifnum\var=0
We have a zero.
\fi

\end{document}


A “more modern” version.

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\newrandomvar}{m}
{
\tl_new:N #1
\tl_set:Nx #1 { \int_rand:nn { 0 } { 1 } }
}
\NewExpandableDocumentCommand{\vartest}{mmm}
{
\int_compare:nTF { #1 = 0 } { #2 } { #3 }
}
\ExplSyntaxOff

\begin{document}

\newrandomvar{\var}

\ifnum\var=1
We have a one.
\fi

\ifnum\var=0
We have a zero.
\fi

We have a \vartest{\var}{zero}{one}.

\end{document}

• Perhaps link to the recent \Make...case question, which was also about (non)expansion of macros by \ifx Jul 23, 2020 at 9:20
• @JosephWright The two are related by unexpandability, but there are greater differences: \ifnum performs macro expansion, contrary to \ifx. Jul 23, 2020 at 9:29

A "more modern" version should look like this:

\ifcase \pdfuniformdeviate2 We have zero\or We have one\fi


The pdfTeX primitive \pdfuniformdeviate and TeX primitive \ifcase are used here.

The \pdfuniformdeviate <number> expands to a random number from 0 to <number>-1.

• There are a few issues with \pdfuniformdeviate, which can be massaged out: see github.com/latex3/latex3/blob/master/l3kernel/l3fp-random.dtx Jul 23, 2020 at 10:02
• Try it with XeTeX or LuaTeX. Jul 23, 2020 at 10:33
• I am currently working with LuaTeX and I don't see any difference or problems. The primitives \pdfuniformdeviate, \pdfrandomseed` etc. work exactly as described in pdfTeX manual. Jul 23, 2020 at 10:38