![pdflatex でランダム変数を生成して計算に使用する方法](https://rvso.com/image/281462/pdflatex%20%E3%81%A7%E3%83%A9%E3%83%B3%E3%83%80%E3%83%A0%E5%A4%89%E6%95%B0%E3%82%92%E7%94%9F%E6%88%90%E3%81%97%E3%81%A6%E8%A8%88%E7%AE%97%E3%81%AB%E4%BD%BF%E7%94%A8%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95.png)
私は基本的に、各質問の変数にそれぞれ異なる値を持つワークシートの複数のバージョンを作成しようとしています。これを行うには、ランダム変数を定義し、コンパイルするたびに値が変更され、ワークシートの「新しい」バージョンが印刷されます。
\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}
実行中の出力は次のとおりですサジェマスクラウド: