How to Generate Random Negative Integer?
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:
Another way to do this:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\foreach \x in {1,...,100}{
\pgfmathparse{int(rand * 11)}
\pgfmathresult, }
\end{document}
Two problems:
The fact that you repeatedly got the same results is due to a missing seed. As you are dealing with a pseudo random number generator, you will get the same sequence otherwise.
A quick way to generate random integers between -10 and 10, is to generate ones between 0 and 20 and shift them by -10.
\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\pgfmathsetseed{\number\pdfrandomseed}
\foreach \n in {1,...,100}{
\pgfmathparse{random(0,20)-10}
\pgfmathresult
}
\end{document}