[Tex/LaTex] How to Generate Random Negative Integer

pgfmathrandom numbers

I am trying to create a worksheet constituted of random numbers so that kids can practice integer operations. E.g.

3+-9=?

2x(-5)=?

18/-3=?

Etc.

How do I do this?

Here is what I've tried so far.

\documentclass{minimal}

\usepackage{tikz}

\begin{document}

\pgfmathparse{random(-10,10)}
\pgfmathresult

\end{document}

Two problems.

  1. Why is there an extra 0.0. before the integer?
  2. Why is that random number 7 when my bounds are -10 and 10? Picking 7 repeatedly seems pretty non-random.

Some of this was mentioned in another thread but that thread is now a couple of years old.

Got ideas?

Thanks!

Best Answer

To work around the bug of the random function, you may defined a new randomfixed function:

\tikzset{declare function={randomfixed(\a,\b) = int(random(0,int(\b-\a))+\a);}}

Now, you may generate a random integer between two boundaries with parentheses for negative integer:

\newcommand\randomint[2]{\bgroup%
  \pgfmathsetmacro\myval{randomfixed(#1,#2)}%
  \pgfmathsetmacro\final{(\myval < 0)?"(\myval)":\myval}%
  \final\egroup%
}

You may generate random operators:

\def\ops{{"+","-","\times","/"}}
\newcommand\randomop{\bgroup\pgfmathsetmacro\op{\ops[int(rnd*4)]}\op\egroup}

To change the seed of the pseudo-random generator each second, you may use the \pdfuniformdeviate macro:

\pgfmathsetseed{\pdfuniformdeviate 10000000}

All the code:

\documentclass{article}
\usepackage{tikz}

% fix bug with random(a,b)
\tikzset{declare function={randomfixed(\a,\b) = int(random(0,int(\b-\a))+\a);}}

% get random integer
\newcommand\randomint[2]{\bgroup%
  \pgfmathsetmacro\myval{randomfixed(#1,#2)}%
  \pgfmathsetmacro\final{(\myval < 0)?"(\myval)":\myval}%
  \final\egroup%
}

% get random operator
\def\ops{{"+","-","\times","/"}}
\newcommand\randomop{\bgroup\pgfmathsetmacro\op{\ops[int(rnd*4)]}\op\egroup}

% choose random seed
\pgfmathsetseed{\pdfuniformdeviate 10000000}

\pagestyle{empty}
\begin{document}
\foreach \n in {1,...,10}{
   $\randomint{-10}{10} \randomop{} \randomint{-10}{10} = $\par
}
\end{document}

And a result:

enter image description here

Related Question