如何產生隨機變數然後在 pdflatex 的計算中使用

如何產生隨機變數然後在 pdflatex 的計算中使用

我基本上試圖創建工作表的多個版本,每個版本的每個問題中的變數都有不同的值。為此,我定義了隨機變量,然後每次編譯值時都會更改並列印工作表的“新”版本。

我了解如何透過\pgfmathsetseed{\pdfrandomseed}在所需範圍內使用和定義變數來建立隨機變量,例如\def\A{pgfrandom{1,10}\pgfmathresult}

我遇到的問題是我想在工作表末尾為每個問題產生答案。但它希望使用與原始問題中產生的隨機值不同的隨機值來計算答案。

例如如果我說

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

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

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

我問一個問題:

What is \A + \B?

\answer

它會產生類似......

What is 2 + 12?

5 + 19, 24

那麼我該如何讓它顯示答案a)而不顯示計算本身(即2 + 12)和b)如何讓它在計算答案時不重新產生新的隨機變數?

抱歉,我希望我的問題很清楚。我對這一切都很陌生。任何幫助表示讚賞。謝謝!

答案1

根據你的問題,你可以這樣做:

程式碼

\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}

結果

2 + 12 是什麼?
結果是14

分層的樂趣;)

您可以使用圖層來隱藏答案,直到啟用解決方案圖層(您沒有要求它,所以這只是為了好玩)。

\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}

結果

答案2

解決方案sagetex使用智者。在sagesilent模式中設定變數。\sage排版時透過指令存取文件中的變數。

\documentclass[12point]{article}%
\usepackage{sagetex}%  use Sage for it's math ability
\pagestyle{empty} % remove the page numbers
\begin{document}
\begin{sagesilent}
var('x')
a = Integer(randint(1,9))
b = Integer(randint(1,9))
\end{sagesilent}
% *********** END DEFINE VARIABLES ****************
\noindent What's $\sage{a}+\sage{b}$? $\sage{a}\times\sage{b}$?    $\sage{a}\div\sage{b}$?\\
Answer: $\sage{a}+\sage{b}=\sage{a+b}$, $\sage{a}\times\sage{b}=\sage{a*b}$ and $\sage{a}\div\sage{b}=\sage{a/b}$\\
You can get a decimal for the division $\sage{a}\div\sage{b}\approx\sage{(a/b).n(digits=5)}$
\end{document}

這是運行的輸出Sagemath 雲在此輸入影像描述

相關內容