# Pick Randomly Between -1 or 1

I would like to generate a simple macro to make \x either 1 or -1. But I'm not sure how to do that.

I set up the code below, but I believe it randomly chooses between -1, 0, and 1.

What adjustment do I have to make to make it choose between only -1 and 1?

\documentclass{article}

\usepackage{pgf}
\usepackage{pgffor}

\pgfmathsetseed{\number\pdfrandomseed}

\begin{document}

\pgfmathsetmacro{\x}{int(random(-1,1))}

\x

\end{document}

• And more generally, how would I randomly assign\x a value from a fixed and arbitrary set of constants? Nov 12, 2016 at 1:41
• Yes. I'd like each number in the set to be equally likely. Nov 12, 2016 at 4:44
• I posted code to do exactly that to one of your questions the other day:-) Nov 12, 2016 at 9:07
• You mention picking values from "a fixed and arbitrary set of constants" -- what kinds of constants do you have in mind? Numbers, one-dimensional string constants, multi-dimensional structures? Please clarify your objective(s).
– Mico
Nov 13, 2016 at 0:04
• Just a set of numbers. Nov 13, 2016 at 5:37

There is a PGF math function to choose randomly from a list of items. This can be used to solve the general problem:

\documentclass{article}
\usepackage{pgffor}
\begin{document}
\pgfmathdeclarerandomlist{ones}{{-1}{1}}
\foreach \x in {1,...,10}{
\pgfmathrandomitem{\choice}{ones}
\choice\space
}

\pgfmathdeclarerandomlist{choices}{{1}{0}{-1}{2}{-2}}
\foreach\x in {1,...,10}{
\pgfmathrandomitem{\choice}{choices}
\choice\space
}
\end{document}



\randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF}
\randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF}
\randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF}
\randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF}
\randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF}
\randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF} \randomelement{ABCDEF}

\end{document}