Debian Codegraph @

texmf-dist/source/latex/l3kernel/l3fp-random.dtx

raw
1 % \iffalse meta-comment
2 %
3 %% File: l3fp-random.dtx
4 %
5 % Copyright (C) 2016-2026 The LaTeX Project
6 %
7 % It may be distributed and/or modified under the conditions of the
8 % LaTeX Project Public License (LPPL), either version 1.3c of this
9 % license or (at your option) any later version. The latest version
10 % of this license is in the file
11 %
12 % https://www.latex-project.org/lppl.txt
13 %
14 % This file is part of the "l3kernel bundle" (The Work in LPPL)
15 % and all files in that bundle must be distributed together.
16 %
17 % -----------------------------------------------------------------------
18 %
19 % The development version of the bundle can be found at
20 %
21 % https://github.com/latex3/latex3
22 %
23 % for those people who are interested.
24 %
25 %<*driver>
26 \documentclass[full,kernel]{l3doc}
27 \begin{document}
28 \DocInput{\jobname.dtx}
29 \end{document}
30 %</driver>
31 % \fi
32 %
33 % \title{^^A
34 % The \pkg{l3fp-random} module\\
35 % Floating point random numbers
36 % }
37 % \author{^^A
38 % The \LaTeX{} Project\thanks
39 % {^^A
40 % E-mail:
41 % \href{mailto:[email protected]}
42 % {[email protected]}^^A
43 % }^^A
44 % }
45 % \date{Released 2026-05-15}
46 %
47 % \maketitle
48 %
49 % \begin{documentation}
50 %
51 % \end{documentation}
52 %
53 % \begin{implementation}
54 %
55 % \section{\pkg{l3fp-random} implementation}
56 %
57 % \begin{macrocode}
58 %<*code>
59 % \end{macrocode}
60 %
61 % \begin{macrocode}
62 %<@@=fp>
63 % \end{macrocode}
64 %
65 % \begin{macro}[EXP]{\@@_parse_word_rand:N , \@@_parse_word_randint:N}
66 % Those functions may receive a variable number of arguments. We
67 % won't use the argument~|?|.
68 % \begin{macrocode}
69 \cs_new:Npn \@@_parse_word_rand:N
70 { \@@_parse_function:NNN \@@_rand_o:Nw ? }
71 \cs_new:Npn \@@_parse_word_randint:N
72 { \@@_parse_function:NNN \@@_randint_o:Nw ? }
73 % \end{macrocode}
74 % \end{macro}
75 %
76 % \subsection{Engine support}
77 %
78 % Obviously, every word \enquote{random} below means
79 % \enquote{pseudo-random}, as we have no access to entropy (except a
80 % very unreliable source of entropy: the time it takes to run some
81 % code).
82 %
83 % The primitive random number generator (RNG) is provided as
84 % \cs{tex_uniformdeviate:D}. Under the hood, it maintains an array of
85 % $55$ $28$-bit numbers, updated with a linear recursion relation
86 % (similar to Fibonacci numbers) modulo $2^{28}$. When
87 % \cs{tex_uniformdeviate:D} \meta{integer} is called (for brevity denote
88 % by~$N$ the \meta{integer}), the next $28$-bit number is read from the
89 % array, scaled by $N/2^{28}$, and rounded. To prevent $0$ and $N$ from
90 % appearing half as often as other numbers, they are both mapped to the
91 % result~$0$.
92 %
93 % This process means that \cs{tex_uniformdeviate:D} only gives a uniform
94 % distribution from $0$ to $N-1$ if $N$ is a divisor of $2^{28}$, so we
95 % will mostly call the RNG with such power of~$2$ arguments. If $N$
96 % does not divide $2^{28}$, then the relative non-uniformity (difference
97 % between probabilities of getting different numbers) is about
98 % $N/2^{28}$. This implies that detecting deviation from $1/N$ of the
99 % probability of a fixed value X requires about $2^{56}/N$ random
100 % trials. But collective patterns can reduce this to about
101 % $2^{56}/N^2$. For instance with $N=3\times 2^{k}$, the modulo~$3$
102 % repartition of such random numbers is biased with a non-uniformity
103 % about $2^k/2^{28}$ (which is much worse than the circa $3/2^{28}$
104 % non-uniformity from taking directly $N=3$). This is detectable after
105 % about $2^{56}/2^{2k} = 9\cdot 2^{56}/N^2$ random numbers. For $k=15$,
106 % $N=98304$, this means roughly $2^{26}$ calls to the RNG
107 % (experimentally this takes at the very least 16 seconds on a 2 giga-hertz
108 % processor). While this bias is not quite problematic, it is
109 % uncomfortably close to being so, and it becomes worse as $N$ is
110 % increased. In our code, we shall thus combine several results from
111 % the RNG\@.
112 %
113 % The RNG has three types of unexpected correlations. First, everything
114 % is linear modulo~$2^{28}$, hence the lowest $k$ bits of the random
115 % numbers only depend on the lowest $k$ bits of the seed (and of course
116 % the number of times the RNG was called since setting the seed). The
117 % recommended way to get a number from $0$ to $N-1$ is thus to scale the
118 % raw $28$-bit integer, as the engine's RNG does. We will go further
119 % and in fact typically we discard some of the lowest bits.
120 %
121 % Second, suppose that we call the RNG with the same argument~$N$ to get
122 % a set of $K$ integers in $[0,N-1]$ (throwing away repeats), and
123 % suppose that $N>K^3$ and $K>55$. The recursion used to construct more
124 % $28$-bit numbers from previous ones is linear:
125 % $x_n = x_{n-55} - x_{n-24}$ or $x_n = x_{n-55}-x_{n-24}+2^{28}$.
126 % After rescaling and rounding we find that the result $N_n\in[0,N-1]$
127 % is among $N_{n-55} - N_{n-24} + \{-1,0,1\}$ modulo~$N$ (a more
128 % detailed analysis shows that $0$ appears with frequency close
129 % to~$3/4$). The resulting set thus has more triplets $(a,b,c)$ than
130 % expected obeying $a=b+c$ modulo~$N$. Namely it will have of order
131 % $(K-55)\times 3/4$ such triplets, when one would expect $K^3/(6N)$.
132 % This starts to be detectable around $N=2^{18}>55^3$ (earlier if one
133 % keeps track of positions too, but this is more subtle than it looks
134 % because the array of $28$-bit integers is read backwards by the
135 % engine). Hopefully the correlation is subtle enough to not affect
136 % realistic documents so we do not specifically mitigate against this.
137 % Since we typically use two calls to the RNG per \cs{int_rand:nn} we
138 % would need to investigate linear relations between the $x_{2n}$ on the
139 % one hand and between the $x_{2n+1}$ on the other hand. Such relations
140 % will have more complicated coefficients than $\pm 1$, which alleviates
141 % the issue.
142 %
143 % Third, consider successive batches of $165$ calls to the RNG (with
144 % argument $2^{28}$ or with argument~$2$ for instance), then most
145 % batches have more odd than even numbers. Note that this does not mean
146 % that there are more odd than even numbers overall. Similar issues are
147 % discussed in Knuth's TAOCP volume 2 near exercise 3.3.2-31. We do not
148 % have any mitigation strategy for this.
149 %
150 % Ideally, our algorithm should be:
151 % \begin{itemize}
152 % \item Uniform. The result should be as uniform as possible assuming
153 % that the RNG's underlying $28$-bit integers are uniform.
154 % \item Uncorrelated. The result should not have detectable
155 % correlations between different seeds, similar to the lowest-bit ones
156 % mentioned earlier.
157 % \item Quick. The algorithm should be fast in \TeX{}, so no
158 % \enquote{bit twiddling}, but \enquote{digit twiddling} is ok.
159 % \item Simple. The behavior must be documentable precisely.
160 % \item Predictable. The number of calls to the RNG should be the same
161 % for any \cs{int_rand:nn}, because then the algorithm can be modified
162 % later without changing the result of other uses of the RNG\@.
163 % \item Robust. It should work even for \cs{int_rand:nn} |{| |-|
164 % \cs{c_max_int} |}| |{| \cs{c_max_int} |}| where the range is not
165 % representable as an integer. In fact, we also provide later a
166 % floating-point |randint| whose range can go all the way up to
167 % $2\times 10^{16}-1$ possible values.
168 % \end{itemize}
169 % Some of these requirements conflict. For instance, uniformity cannot
170 % be achieved with a fixed number of calls to the RNG\@.
171 %
172 % Denote by $\operatorname{random}(N)$ one call to
173 % \cs{tex_uniformdeviate:D} with argument~$N$, and by
174 % $\operatorname{ediv}(p,q)$ the \eTeX{} rounding division giving
175 % $\lfloor p/q+1/2\rfloor$. Denote by $\meta{min}$, $\meta{max}$ and
176 % $R=\meta{max}-\meta{min}+1$ the arguments of \cs{int_min:nn} and the
177 % number of possible outcomes. Note that $R\in [1,2^{32}-1]$ cannot
178 % necessarily be represented as an integer (however, $R-2^{31}$ can).
179 % Our strategy is to get two $28$-bit integers $X$ and $Y$ from the RNG,
180 % split each into $14$-bit integers, as $X=X_1\times 2^{14}+X_0$ and
181 % $Y=Y_1\times 2^{14}+Y_0$ then return essentially
182 % $\meta{min} + \lfloor R (X_1\times 2^{-14} + Y_1\times 2^{-28} +
183 % Y_0\times 2^{-42} + X_0\times 2^{-56})\rfloor$. For small~$R$ the
184 % $X_0$ term has a tiny effect so we ignore it and we can compute
185 % $R\times Y/2^{28}$ much more directly by $\operatorname{random}(R)$.
186 % \begin{itemize}
187 % \item If $R \leq 2^{17}-1$ then return
188 % $\operatorname{ediv}(R\operatorname{random}(2^{14}) +
189 % \operatorname{random}(R) + 2^{13}, 2^{14}) - 1 + \meta{min}$. The
190 % shifts by $2^{13}$ and $-1$ convert \eTeX{} division to truncated
191 % division. The bound on $R$ ensures that the number obtained after
192 % the shift is less than \cs{c_max_int}. The non-uniformity is at
193 % most of order $2^{17}/2^{42} = 2^{-25}$.
194 % \item Split $R=R_2\times 2^{28}+R_1\times 2^{14}+R_0$, where
195 % $R_2\in [0,15]$. Compute
196 % $\meta{min} + R_2 X_1 2^{14} + (R_2 Y_1 + R_1 X_1) +
197 % \operatorname{ediv}(R_2 Y_0 + R_1 Y_1 + R_0 X_1 +
198 % \operatorname{ediv}(R_2 X_0 + R_0 Y_1 + \operatorname{ediv}((2^{14}
199 % R_1 + R_0) (2^{14} Y_0 + X_0), 2^{28}), 2^{14}), 2^{14})$ then map a
200 % result of $\meta{max}+1$ to $\meta{min}$. Writing each
201 % $\operatorname{ediv}$ in terms of truncated division with a shift,
202 % and using
203 % $\lfloor(p+\lfloor r/s\rfloor)/q\rfloor =
204 % \lfloor(ps+r)/(sq)\rfloor$, what we compute is equal to
205 % $\lfloor\meta{exact}+2^{-29}+2^{-15}+2^{-1}\rfloor$ with
206 % $\meta{exact}=\meta{min} + R \times 0.X_1Y_1Y_0X_0$. Given we map
207 % $\meta{max}+1$ to $\meta{min}$, the shift has no effect on
208 % uniformity. The non-uniformity is bounded by $R/2^{56}<2^{-24}$. It
209 % may be possible to speed up the code by dropping tiny terms such as
210 % $R_0 X_0$, but the analysis of non-uniformity proves too difficult.
211 %
212 % To avoid the overflow when the computation yields $\meta{max}+1$
213 % with $\meta{max}=2^{31}-1$ (note that $R$ is then arbitrary), we
214 % compute the result in two pieces. Compute
215 % $\meta{first} = \meta{min} + R_2 X_1 2^{14}$ if $R_2<8$ or
216 % $\meta{min} + 8 X_1 2^{14} + (R_2-8) X_1 2^{14}$ if $R_2\geq 8$, the
217 % expressions being chosen to avoid overflow. Compute
218 % $\meta{second} = R_2 Y_1 + R_1 X_1 + \operatorname{ediv}({\dots})$,
219 % at most
220 % $R_2 2^{14} + R_1 2^{14} + R_0\leq 2^{28} + 15\times 2^{14} - 1$,
221 % not at risk of overflowing. We have
222 % $\meta{first}+\meta{second}=\meta{max}+1=\meta{min}+R$ if and only
223 % if $\meta{second} = R1 2^{14} + R_0 + R_2 2^{14}$ and
224 % $2^{14} R_2 X_1 = 2^{28} R_2 - 2^{14} R_2$ (namely $R_2=0$ or
225 % $X_1=2^{14}-1$). In that case, return \meta{min}, otherwise return
226 % $\meta{first}+\meta{second}$, which is safe because it is at most
227 % \meta{max}. Note that the decision of what to return does not need
228 % \meta{first} explicitly so we don't actually compute it, just put it
229 % in an integer expression in which \meta{second} is eventually added
230 % (or not).
231 % \item To get a floating point number in $[0,1)$ just call the
232 % $R=10000\leq 2^{17}-1$ procedure above to produce four blocks of four
233 % digits.
234 % \item To get an integer floating point number in a range (whose size
235 % can be up to $2\times 10^{16}-1$), work with fixed-point numbers:
236 % get six times four digits to build a fixed point number, multiply by
237 % $R$ and add $\meta{min}$. This requires some care because
238 % \pkg{l3fp-extended} only supports non-negative numbers.
239 % \end{itemize}
240 %
241 % \begin{variable}{\c__kernel_randint_max_int}
242 % Constant equal to $2^{17}-1$, the maximal size of a range that
243 % \cs{int_range:nn} can do with its \enquote{simple} algorithm.
244 % \begin{macrocode}
245 \int_const:Nn \c__kernel_randint_max_int { 131071 }
246 % \end{macrocode}
247 % \end{variable}
248 %
249 % \begin{macro}[EXP]{\__kernel_randint:n}
250 % Used in an integer expression, \cs{__kernel_randint:n} |{|$R$|}|
251 % gives a random number
252 % $1+\lfloor(R\operatorname{random}(2^{14}) +
253 % \operatorname{random}(R))/2^{14}\rfloor$ that is in $[1,R]$.
254 % Previous code was computing $\lfloor p/2^{14}\rfloor$ as
255 % $\operatorname{ediv}(p-2^{13},2^{14})$ but that wrongly gives $-1$
256 % for $p=0$.
257 % \begin{macrocode}
258 \cs_new:Npn \__kernel_randint:n #1
259 {
260 (#1 * \tex_uniformdeviate:D 16384
261 + \tex_uniformdeviate:D #1 + 8192 ) / 16384
262 }
263 % \end{macrocode}
264 % \end{macro}
265 %
266 % \begin{macro}[EXP]
267 % {\@@_rand_myriads:n, \@@_rand_myriads_loop:w, \@@_rand_myriads_get:w}
268 % Used as \cs{@@_rand_myriads:n} |{XXX}| with one letter |X|
269 % (specifically) per block of four digit we want; it expands to \cs{@@_sep:}
270 % followed by the requested number of brace groups, each containing
271 % four (pseudo-random) digits. Digits are produced as a random number
272 % in $[10000,19999]$ for the usual reason of preserving leading zeros.
273 % \begin{macrocode}
274 \cs_new:Npn \@@_rand_myriads:n #1
275 { \@@_rand_myriads_loop:w #1 \prg_break: X \prg_break_point: \@@_sep: }
276 \cs_new:Npn \@@_rand_myriads_loop:w #1 X
277 {
278 #1
279 \exp_after:wN \@@_rand_myriads_get:w
280 \int_value:w \@@_int_eval:w 9999 +
281 \__kernel_randint:n { 10000 }
282 \@@_rand_myriads_loop:w
283 }
284 \cs_new:Npn \@@_rand_myriads_get:w 1 #1 \@@_sep: { \@@_sep: {#1} }
285 % \end{macrocode}
286 % \end{macro}
287 %
288 % \subsection{Random floating point}
289 %
290 % \begin{macro}[EXP]{\@@_rand_o:Nw, \@@_rand_o:w}
291 % First we check that |random| was called without argument. Then get
292 % four blocks of four digits and convert that fixed point number to a
293 % floating point number (this correctly sets the exponent). This has
294 % a minor bug: if all of the random numbers are zero then the result
295 % is correctly~$0$ but it raises the \texttt{underflow} flag; it
296 % should not do that.
297 % \begin{macrocode}
298 \cs_new:Npn \@@_rand_o:Nw ? #1 @
299 {
300 \tl_if_empty:nTF {#1}
301 {
302 \exp_after:wN \@@_rand_o:w
303 \exp:w \exp_end_continue_f:w
304 \@@_rand_myriads:n { XXXX } { 0000 } { 0000 } \@@_sep: 0
305 }
306 {
307 \@@_error_num_args:ffff { rand } { 0 } { 0 }
308 { \@@_array_count:n {#1} }
309 \exp_after:wN \c_nan_fp
310 }
311 }
312 \cs_new:Npn \@@_rand_o:w \@@_sep:
313 {
314 \exp_after:wN \@@_sanitize:Nw
315 \exp_after:wN 0
316 \int_value:w \@@_int_eval:w \c_zero_int
317 \@@_fixed_to_float_o:wN
318 }
319 % \end{macrocode}
320 % \end{macro}
321 %
322 % \subsection{Random integer}
323 %
324 % \begin{macro}[EXP]{\@@_randint_o:Nw}
325 % \begin{macro}[EXP]
326 % {
327 % \@@_randint_default:w,
328 % \@@_randint_badarg:w,
329 % \@@_randint_o:w,
330 % \@@_randint_auxi_o:ww,
331 % \@@_randint_auxii:wn,
332 % \@@_randint_auxiii_o:ww,
333 % \@@_randint_auxiv_o:ww,
334 % \@@_randint_auxv_o:w,
335 % }
336 % Enforce that there is one argument (then add first argument~$1$)
337 % or two arguments. Call \cs{@@_randint_badarg:w} on each; this
338 % function inserts |1| \cs{exp_stop_f:} to end the \cs{if_case:w}
339 % statement if either the argument is not an integer or if its
340 % absolute value is $\geq 10^{16}$. Also bail out if
341 % \cs{@@_compare_back:ww} yields~|1|, meaning that the bounds are
342 % not in the right order. Otherwise an auxiliary converts each
343 % argument times $10^{-16}$ (hence the shift in exponent) to a
344 % $24$-digit fixed point number (see \pkg{l3fp-extended}).
345 % Then compute the number of choices, $\meta{max}+1-\meta{min}$.
346 % Create a random $24$-digit fixed-point number with
347 % \cs{@@_rand_myriads:n}, then use a fused multiply-add instruction
348 % to multiply the number of choices to that random number and add it
349 % to \meta{min}. Then truncate to $16$ digits (namely select the
350 % integer part of $10^{16}$ times the result) before converting back
351 % to a floating point number (\cs{@@_sanitize:Nw} takes care of zero).
352 % To avoid issues with negative numbers, add $1$ to all fixed point
353 % numbers (namely $10^{16}$ to the integers they represent), except
354 % of course when it is time to convert back to a float.
355 % \begin{macrocode}
356 \cs_new:Npn \@@_randint_o:Nw ?
357 {
358 \@@_parse_function_one_two:nnw
359 { randint }
360 { \@@_randint_default:w \@@_randint_o:w }
361 }
362 \cs_new:Npn \@@_randint_default:w #1 { \exp_after:wN #1 \c_one_fp }
363 \cs_new:Npn \@@_randint_badarg:w \s_@@ \@@_chk:w #1#2#3\@@_sep:
364 {
365 \@@_int:wTF \s_@@ \@@_chk:w #1#2#3\@@_sep:
366 {
367 \if_meaning:w 1 #1
368 \if_int_compare:w
369 \@@_use_i_until_s:nw #3 \@@_sep: > \c_@@_prec_int
370 \c_one_int
371 \fi:
372 \fi:
373 }
374 { \c_one_int }
375 }
376 \cs_new:Npn \@@_randint_o:w #1\@@_sep: #2\@@_sep: @
377 {
378 \if_case:w
379 \@@_randint_badarg:w #1\@@_sep:
380 \@@_randint_badarg:w #2\@@_sep:
381 \if:w 1 \@@_compare_back:ww #2\@@_sep: #1\@@_sep: \c_one_int \fi:
382 \c_zero_int
383 \@@_randint_auxi_o:ww #1\@@_sep: #2\@@_sep:
384 \or:
385 \@@_invalid_operation_tl_o:ff
386 { randint } { \@@_array_to_clist:n { #1\@@_sep: #2\@@_sep: } }
387 \exp:w
388 \fi:
389 \exp_after:wN \exp_end:
390 }
391 \cs_new:Npn \@@_randint_auxi_o:ww #1 \@@_sep: #2 \@@_sep: #3 \exp_end:
392 {
393 \fi:
394 \@@_randint_auxii:wn #2 \@@_sep:
395 { \@@_randint_auxii:wn #1 \@@_sep: \@@_randint_auxiii_o:ww }
396 }
397 \cs_new:Npn \@@_randint_auxii:wn \s_@@ \@@_chk:w #1#2#3#4 \@@_sep:
398 {
399 \if_meaning:w 0 #1
400 \exp_after:wN \use_i:nn
401 \else:
402 \exp_after:wN \use_ii:nn
403 \fi:
404 { \exp_after:wN \@@_fixed_continue:wn \c_@@_one_fixed_tl }
405 {
406 \exp_after:wN \@@_ep_to_fixed:wwn
407 \int_value:w \@@_int_eval:w
408 #3 - \c_@@_prec_int , #4 {0000} {0000} \@@_sep:
409 {
410 \if_meaning:w 0 #2
411 \exp_after:wN \use_i:nnnn
412 \exp_after:wN \@@_fixed_add_one:wN
413 \fi:
414 \exp_after:wN \@@_fixed_sub:wwn \c_@@_one_fixed_tl
415 }
416 \@@_fixed_continue:wn
417 }
418 }
419 \cs_new:Npn \@@_randint_auxiii_o:ww #1 \@@_sep: #2 \@@_sep:
420 {
421 \@@_fixed_add:wwn #2 \@@_sep:
422 {0000} {0000} {0000} {0001} {0000} {0000} \@@_sep:
423 \@@_fixed_sub:wwn #1 \@@_sep:
424 {
425 \exp_after:wN \use_i:nn
426 \exp_after:wN \@@_fixed_mul_add:wwwn
427 \exp:w \exp_end_continue_f:w \@@_rand_myriads:n { XXXXXX } \@@_sep:
428 }
429 #1 \@@_sep:
430 \@@_randint_auxiv_o:ww
431 #2 \@@_sep:
432 \@@_randint_auxv_o:w #1 \@@_sep: @
433 }
434 \cs_new:Npn \@@_randint_auxiv_o:ww #1#2#3#4#5 \@@_sep: #6#7#8#9
435 {
436 \if_int_compare:w
437 \if_int_compare:w #1#2 > #6#7 \exp_stop_f: 1 \else:
438 \if_int_compare:w #1#2 < #6#7 \exp_stop_f: - \fi: \fi:
439 #3#4 > #8#9 \exp_stop_f:
440 \@@_use_i_until_s:nw
441 \fi:
442 \@@_randint_auxv_o:w {#1}{#2}{#3}{#4}#5
443 }
444 \cs_new:Npn \@@_randint_auxv_o:w #1#2#3#4#5 \@@_sep: #6 @
445 {
446 \exp_after:wN \@@_sanitize:Nw
447 \int_value:w
448 \if_int_compare:w #1 < 10000 \exp_stop_f:
449 2
450 \else:
451 0
452 \exp_after:wN \exp_after:wN
453 \exp_after:wN \@@_reverse_args:Nww
454 \fi:
455 \exp_after:wN \@@_fixed_sub:wwn \c_@@_one_fixed_tl
456 {#1} {#2} {#3} {#4} {0000} {0000} \@@_sep:
457 {
458 \exp_after:wN \exp_stop_f:
459 \int_value:w \@@_int_eval:w \c_@@_prec_int
460 \@@_fixed_to_float_o:wN
461 }
462 0
463 \exp:w \exp_after:wN \exp_end:
464 }
465 % \end{macrocode}
466 % \end{macro}
467 % \end{macro}
468 %
469 % \begin{macro}{\int_rand:nn, \@@_randint:ww}
470 % Evaluate the argument and filter out the case where the lower
471 % bound~|#1| is more than the upper bound~|#2|. Then determine
472 % whether the range is narrower than \cs{c__kernel_randint_max_int};
473 % |#2-#1| may overflow for very large positive~|#2| and negative~|#1|.
474 % If the range is narrow, call \cs{__kernel_randint:n} \Arg{choices}
475 % where \meta{choices} is the number of possible outcomes. If the
476 % range is wide, use somewhat slower code.
477 % \begin{macrocode}
478 \cs_new:Npn \int_rand:nn #1#2
479 {
480 \int_eval:n
481 {
482 \exp_after:wN \@@_randint:ww
483 \int_value:w \int_eval:n {#1} \exp_after:wN \@@_sep:
484 \int_value:w \int_eval:n {#2} \@@_sep:
485 }
486 }
487 \cs_new:Npn \@@_randint:ww #1\@@_sep: #2\@@_sep:
488 {
489 \if_int_compare:w #1 > #2 \exp_stop_f:
490 \msg_expandable_error:nnnn
491 { kernel } { randint-backward-range } {#1} {#2}
492 \@@_randint:ww #2\@@_sep: #1\@@_sep:
493 \else:
494 \if_int_compare:w \@@_int_eval:w #2
495 \if_int_compare:w #1 > \c_zero_int
496 - #1 < \@@_int_eval:w
497 \else:
498 < \@@_int_eval:w #1 +
499 \fi:
500 \c__kernel_randint_max_int
501 \@@_int_eval_end:
502 \__kernel_randint:n
503 { \@@_int_eval:w #2 - #1 + 1 \@@_int_eval_end: }
504 - 1 + #1
505 \else:
506 \__kernel_randint:nn {#1} {#2}
507 \fi:
508 \fi:
509 }
510 % \end{macrocode}
511 % \end{macro}
512 %
513 % \begin{macro}
514 % {
515 % \__kernel_randint:nn, \@@_randint_split_o:Nw, \@@_randint_split_aux:w,
516 % \@@_randinat_wide_aux:w, \@@_randinat_wide_auxii:w,
517 % }
518 % Any $n\in[-2^{31}+1,2^{31}-1]$ is uniquely written as
519 % $2^{14}n_1+n_2$ with $n_1\in[-2^{17},2^{17}-1]$ and
520 % $n_2\in[0,2^{14}-1]$. Calling \cs{@@_randint_split_o:Nw} $n$ \cs{@@_sep:}
521 % gives $n_1$\cs{@@_sep:} $n_2$\cs{@@_sep:} and expands the next token once. We do this
522 % for two random numbers and apply \cs{@@_randint_split_o:Nw} twice to
523 % fully decompose the range~$R$. One subtlety is that we compute
524 % $R-2^{31}=\meta{max}-\meta{min}-(2^{31}-1)\in[-2^{31}+1,2^{31}-1]$
525 % rather than $R$ to avoid overflow.
526 %
527 % Then we have \cs{@@_randint_wide_aux:w} \meta{X_1}\cs{@@_sep:}\meta{X_0}\cs{@@_sep:}
528 % \meta{Y_1}\cs{@@_sep:}\meta{Y_0}\cs{@@_sep:}
529 % \meta{R_2}\cs{@@_sep:}\meta{R_1}\cs{@@_sep:}\meta{R_0}\cs{@@_sep:}|.|
530 % and we apply the algorithm described earlier.
531 % \begin{macrocode}
532 \cs_new:Npn \__kernel_randint:nn #1#2
533 {
534 #1
535 \exp_after:wN \@@_randint_wide_aux:w
536 \int_value:w
537 \exp_after:wN \@@_randint_split_o:Nw
538 \tex_uniformdeviate:D 268435456 \@@_sep:
539 \int_value:w
540 \exp_after:wN \@@_randint_split_o:Nw
541 \tex_uniformdeviate:D 268435456 \@@_sep:
542 \int_value:w
543 \exp_after:wN \@@_randint_split_o:Nw
544 \int_value:w \@@_int_eval:w 131072 +
545 \exp_after:wN \@@_randint_split_o:Nw
546 \int_value:w
547 \__kernel_int_add:nnn {#2} { -#1 } { -\c_max_int } \@@_sep:
548 .
549 }
550 \cs_new:Npn \@@_randint_split_o:Nw #1#2 \@@_sep:
551 {
552 \if_meaning:w 0 #1
553 0 \exp_after:wN \@@_sep: \int_value:w 0
554 \else:
555 \exp_after:wN \@@_randint_split_aux:w
556 \int_value:w \@@_int_eval:w (#1#2 - 8192) / 16384 \@@_sep:
557 + #1#2
558 \fi:
559 \exp_after:wN \@@_sep:
560 }
561 \cs_new:Npn \@@_randint_split_aux:w #1 \@@_sep:
562 {
563 #1 \exp_after:wN \@@_sep:
564 \int_value:w \@@_int_eval:w - #1 * 16384
565 }
566 \cs_new:Npn \@@_randint_wide_aux:w
567 #1\@@_sep:#2\@@_sep: #3\@@_sep:#4\@@_sep:
568 #5\@@_sep:#6\@@_sep:#7\@@_sep: .
569 {
570 \exp_after:wN \@@_randint_wide_auxii:w
571 \int_value:w \@@_int_eval:w #5 * #3 + #6 * #1 +
572 (#5 * #4 + #6 * #3 + #7 * #1 +
573 (#5 * #2 + #7 * #3 +
574 (16384 * #6 + #7) * (16384 * #4 + #2) / 268435456) / 16384
575 ) / 16384 \exp_after:wN \@@_sep:
576 \int_value:w \@@_int_eval:w (#5 + #6) * 16384 + #7 \@@_sep:
577 #1 \@@_sep: #5 \@@_sep:
578 }
579 \cs_new:Npn \@@_randint_wide_auxii:w
580 #1\@@_sep: #2\@@_sep: #3\@@_sep: #4\@@_sep:
581 {
582 \if_int_odd:w 0
583 \if_int_compare:w #1 = #2 \else: \exp_stop_f: \fi:
584 \if_int_compare:w #4 = \c_zero_int 1 \fi:
585 \if_int_compare:w #3 = 16383 ~ 1 \fi:
586 \exp_stop_f:
587 \exp_after:wN \prg_break:
588 \fi:
589 \if_int_compare:w #4 < 8 \exp_stop_f:
590 + #4 * #3 * 16384
591 \else:
592 + 8 * #3 * 16384 + (#4 - 8) * #3 * 16384
593 \fi:
594 + #1
595 \prg_break_point:
596 }
597 % \end{macrocode}
598 % \end{macro}
599 %
600 % \begin{macro}{\int_rand:n, \@@_randint:n}
601 % Similar to \cs{int_rand:nn}, but needs fewer checks.
602 % \begin{macrocode}
603 \cs_new:Npn \int_rand:n #1
604 {
605 \int_eval:n
606 { \exp_args:Nf \@@_randint:n { \int_eval:n {#1} } }
607 }
608 \cs_new:Npn \@@_randint:n #1
609 {
610 \if_int_compare:w #1 < \c_one_int
611 \msg_expandable_error:nnnn
612 { kernel } { randint-backward-range } { 1 } {#1}
613 \@@_randint:ww #1\@@_sep: 1\@@_sep:
614 \else:
615 \if_int_compare:w #1 > \c__kernel_randint_max_int
616 \__kernel_randint:nn { 1 } {#1}
617 \else:
618 \__kernel_randint:n {#1}
619 \fi:
620 \fi:
621 }
622 % \end{macrocode}
623 % \end{macro}
624 %
625 % \begin{macrocode}
626 %</code>
627 % \end{macrocode}
628 %
629 % \end{implementation}
630 %
631 % \PrintChanges
632 %
633 % \PrintIndex