[Tex/LaTex] How to Obtain a Random Non-Zero Integer

random numberstikz-pgf

I would like \a to generate a random non-zero integer between, say, -5 and 5 inclusively.

One way to do this would be to make a list of all integers from -5 to 5 but excluding zero, then drawing randomly from that list. This is OK, but would not scale very well if I wanted \a to be a non-zero integer between, say, -500 and 500.

Is there an easier adjustment to make to the following code to specifically exclude the possibility of \a=0?

\documentclass{article}

\usepackage{ifthen}
\usepackage{pgf}
 \pgfmathsetseed{\number\pdfrandomseed}

\newcommand{\InitVariables}
{\pgfmathsetmacro{\a}{int(random(0,10)-5)}}

\begin{document}

\InitVariables

\a

\end{document}

Best Answer

Choose a random number between 1 and X (thereby avoiding 0) and multiply it with 1 or -1 based on a uniform distribution (thereby obtaining a sign):

enter image description here

\documentclass{article}

\usepackage{tikz}
\pgfmathsetseed{\number\pdfrandomseed}

\newcommand{\InitVariables}{%
  \pgfmathsetmacro{\a}{int(ifthenelse(rand > 0, 1, -1)*random(1,5))}%
}

\begin{document}

\foreach \x in {1,...,100}{\InitVariables$\a$ }

\end{document}
Related Question