[Tex/LaTex] How to Generate Random Variables then Use in Calculations in pdflatex

pdftexrandom numberstikz-pgf

I'm basically trying to create multiple versions of a worksheet, each with different values for the variables in each question. To do this I'm defining random variables, then each time I compile the values change and I print a "new" version of the worksheet.

I understand how to create the random variables by using \pgfmathsetseed{\pdfrandomseed} and defining my variables in my desired ranges as e.g. \def\A{pgfrandom{1,10}\pgfmathresult}

The problem I run into is that I want to generate an answer for each problem at the end of the worksheet. But it wants to do the calculation for the answer with a different random value than the one generated in the original question.

e.g. If I say

\def\A{pgfrandom{1,10}\pgfmathresult}

\def\B{pgfrandom{10,20}\pgfmathresult}

\def\answer{\A + \B, \pgfmathresult}

and I ask the question:

What is \A + \B?

\answer

It will produce something like….

What is 2 + 12?

5 + 19, 24

So how do I get it to display the answer a) without showing the calculation itself (i.e. 2 + 12) and b) how do I get it to not re-generate a new random variable when computing the answer?

Sorry, I hope my questions are clear. I'm new to all this. Any help is appreciated. Thanks!

Best Answer

Based on your question you could do this:

Code

\documentclass{article}

\usepackage{pgf}

\pgfmathsetseed{\number\pdfrandomseed} % provide seed for pseudo random generator
% (change to constant, to get the same random numbers on every time compiling)

% new command to init variables
\newcommand\initVariables{%
    \pgfmathsetmacro{\A}{random(1,10)}%
    \pgfmathsetmacro{\B}{random(10,20)}%
}

\newcommand\answer{\pgfmathprint{int(\A + \B)}} % define command to calculate result


\begin{document}
\initVariables % initialize variables (do this every time you need new numbers)
What is $\A + \B$?

Result is \answer
\end{document}

Result

What is 2 + 12?
Result is 14

Fun with layers ;)

You could use layers to hide the answer, until the solution layer is enabled (you didn't ask for it, so this is just for fun).

\documentclass{article}

\usepackage{pgf}
\usepackage{ocg-p}

\pgfmathsetseed{\number\pdfrandomseed} % provide seed for pseudo random generator 

% new command to init variables
\newcommand\initVariables{%
    \pgfmathsetmacro{\A}{random(1,10)}%
    \pgfmathsetmacro{\B}{random(10,20)}%
}

\newcommand\answer{\pgfmathprint{int(\A + \B)}} %define command to calculate result
\begin{document}
\initVariables%initialize variables (do this every time you need new numbers)
What is $\A + \B$?

Result is 
\begin{ocg}{result layer}{1}{0}
\answer
\end{ocg}

\end{document}

result

Related Question