
這是後續我關於隨機數的最後一篇文章。
我的新問題是:
假設我想\n
(某種程度上)隨機生成,這樣
\n
=1 10% 的時間
\n
=2 20% 的時間
\n
=3 30% 的時間
\n
=4 40% 的時間
該代碼使每個可能的值具有\n
相同的可能性。如何權衡上面列出的機率?
\documentclass{minimal}
\setlength\parindent{0pt}
\usepackage{pgffor}
\begin{document}
\pgfmathdeclarerandomlist{choices}{{1}{2}{3}{4}}
\foreach\x in {1,...,50}
{\pgfmathrandomitem{\n}{choices}\n\\}
\end{document}
答案1
您可以對我上一個問題的答案進行變體,並嵌套三個ifthenelse
s。
\documentclass[border=4mm]{article}
\usepackage{pgffor}
\begin{document}
\foreach\x in {1,...,2000} {
\pgfmathsetmacro{\tmp}{rnd}
\pgfmathparse{ifthenelse(\tmp<=0.1,1,ifthenelse(\tmp<=0.3,2,ifthenelse(\tmp<=0.6,3,4)))}\pgfmathresult
}
\end{document}
借用一下egreg的答案:
\documentclass{article}
\usepackage{pgffor}
\begin{document}
\newcounter{1}\newcounter{2}\newcounter{3}\newcounter{4}
\foreach\x in {1,...,2000} {
\pgfmathsetmacro{\tmp}{rnd}
\pgfmathparse{ifthenelse(\tmp<=0.1,1,ifthenelse(\tmp<=0.3,2,ifthenelse(\tmp<=0.6,3,4)))}\pgfmathresult
\stepcounter{\pgfmathresult}
}
1: \the\value{1}\par
2: \the\value{2}\par
3: \the\value{3}\par
4: \the\value{4}\par
\end{document}
答案2
\documentclass{article}
\usepackage{pgffor}
\newcommand{\myrandom}{%
\expandafter\domyrandom\pdfuniformdeviate 10 \domyrandom
}
\def\domyrandom#1\domyrandom{%
\ifcase#1
1\or
2\or
2\or
3\or
3\or
3\or
4\or
4\or
4\or
4\fi
}
\begin{document}
\foreach \x in {1,...,100}{\myrandom\space}
\newcounter{1}\newcounter{2}\newcounter{3}\newcounter{4}
\foreach \x in {1,...,1000}{\stepcounter{\myrandom}}
1: \the\value{1}\par
2: \the\value{2}\par
3: \the\value{3}\par
4: \the\value{4}\par
\end{document}
答案3
雖然我確信有一種直接方法可以產生從 1 到 4 的整數,以便它們的機率為 0.1、0.2、0.3 和 0.4,但間接或兩步法的設定更簡單。首先,隨機產生一個 1 到 10 之間的整數。 (即每個整數都有P=0.1
。)其次,檢查該整數是否分別小於 2、4 和 7,並相應地分配數字“1”、“2”、“3”——並關聯數字“4” ” 與“以上皆非」類別,即整數在7 到10 之間。
這是這個想法的基於 LuaLaTeX 的實作。
\documentclass{article}
\newcommand\x{%
\directlua{x=math.random(10) % draw an integer between 1 and 10
if x<2 then tex.sprint(1) % true if x==1
elseif x<4 then tex.sprint(2) % true if x==2 or 3
elseif x<7 then tex.sprint(3) % true if x==4, 5, or 6
else tex.sprint(4) % true if x==7, 8, 9, or 10
end}}
\begin{document}
\obeylines % just for this example
\x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x
\x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x
\x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x
\x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x; \x, \x, \x, \x, \x
\end{document}
答案4
https://en.wikipedia.org/wiki/Pseudo-random_number_sampling
建立一個 x 值從 0 到 1 的函數,y 值可輸出所需分佈的整數值。然後使用隨機數產生器產生 0 到 1 之間的數字,然後找出函數的值。您的函數可以是一個 100 個元素的數組,其中“x”值乘以 100 並向下舍入...