malachite_nz/integer/random/mod.rs
1// Copyright © 2025 Mikhail Hogrefe
2//
3// This file is part of Malachite.
4//
5// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
6// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
7// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
8
9use crate::integer::Integer;
10use crate::natural::Natural;
11use crate::natural::random::{
12 RandomNaturalsLessThan, StripedRandomNaturalInclusiveRange, get_random_natural_less_than,
13 get_random_natural_with_bits, get_striped_random_natural_from_inclusive_range,
14 get_striped_random_natural_with_bits, random_naturals_less_than,
15 striped_random_natural_inclusive_range,
16};
17use malachite_base::bools::random::{RandomBools, random_bools};
18use malachite_base::num::arithmetic::traits::{PowerOf2, UnsignedAbs};
19use malachite_base::num::basic::traits::{One, Zero};
20use malachite_base::num::conversion::traits::ExactFrom;
21use malachite_base::num::logic::traits::SignificantBits;
22use malachite_base::num::random::geometric::{
23 GeometricRandomNaturalValues, GeometricRandomNegativeSigneds, GeometricRandomNonzeroSigneds,
24 GeometricRandomSignedRange, GeometricRandomSigneds, geometric_random_natural_signeds,
25 geometric_random_negative_signeds, geometric_random_nonzero_signeds,
26 geometric_random_positive_signeds, geometric_random_signed_inclusive_range,
27 geometric_random_signeds, get_geometric_random_signed_from_inclusive_range,
28};
29use malachite_base::num::random::striped::StripedBitSource;
30use malachite_base::num::random::{
31 RandomPrimitiveInts, VariableRangeGenerator, random_primitive_ints,
32};
33use malachite_base::random::Seed;
34
35/// Generates random [`Integer`]s, given an iterator of random signed bit lengths.
36///
37/// The [`Integer`]'s signs are taken from the signs of the bit lengths.
38#[derive(Clone, Debug)]
39pub struct RandomIntegers<I: Iterator<Item = i64>> {
40 bits: I,
41 limbs: RandomPrimitiveInts<u64>,
42}
43
44impl<I: Iterator<Item = i64>> Iterator for RandomIntegers<I> {
45 type Item = Integer;
46
47 fn next(&mut self) -> Option<Integer> {
48 let bits = self.bits.next().unwrap();
49 Some(Integer::from_sign_and_abs(
50 bits >= 0,
51 get_random_natural_with_bits(&mut self.limbs, bits.unsigned_abs()),
52 ))
53 }
54}
55
56/// Generates random natural (non-negative) [`Integer`]s with a specified mean bit length.
57///
58/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
59/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 0. Then an [`Integer`]
60/// is chosen uniformly among all non-negative [`Integer`]s with that bit length. The resulting
61/// distribution resembles a Pareto distribution. It has no mean or higher-order statistics (unless
62/// $m < 1$, which is not typical).
63///
64/// $$
65/// P(n) = \\begin{cases}
66/// 0 & \text{if} \\quad n < 0, \\\\
67/// \\frac{1}{m + 1} & \text{if} \\quad n = 0, \\\\
68/// \\frac{2}{m+1} \\left ( \\frac{m}{2(m+1)} \\right ) ^ {\\lfloor \\log_2 n \\rfloor + 1} &
69/// \\text{otherwise}.
70/// \\end{cases}
71/// $$
72///
73/// The output length is infinite.
74///
75/// # Expected complexity per iteration
76/// $T(n, m) = O(n + m)$
77///
78/// $M(n, m) = O(n / m)$
79///
80/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
81/// `mean_precision_denominator`.
82///
83/// # Panics
84/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, or, if after being reduced
85/// to lowest terms, their sum is greater than or equal to $2^{64}$.
86///
87/// # Examples
88/// ```
89/// use malachite_base::iterators::prefix_to_string;
90/// use malachite_base::random::EXAMPLE_SEED;
91/// use malachite_nz::integer::random::random_natural_integers;
92///
93/// assert_eq!(
94/// prefix_to_string(random_natural_integers(EXAMPLE_SEED, 32, 1), 10),
95/// "[20431208470830262, 2777240, 114, 12184833305054, 1121025855008623490210, \
96/// 13478874522577592, 115311695, 7, 18, 54522366353, ...]"
97/// )
98/// ```
99pub fn random_natural_integers(
100 seed: Seed,
101 mean_bits_numerator: u64,
102 mean_bits_denominator: u64,
103) -> RandomIntegers<GeometricRandomNaturalValues<i64>> {
104 RandomIntegers {
105 bits: geometric_random_natural_signeds(
106 seed.fork("bits"),
107 mean_bits_numerator,
108 mean_bits_denominator,
109 ),
110 limbs: random_primitive_ints(seed.fork("limbs")),
111 }
112}
113
114/// Generates random positive [`Integer`]s with a specified mean bit length.
115///
116/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
117/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 1. Then an [`Integer`]
118/// is chosen uniformly among all positive [`Integer`]s with that bit length. The resulting
119/// distribution resembles a Pareto distribution. It has no mean or higher-order statistics (unless
120/// $m < 2$, which is not typical).
121///
122/// $$
123/// P(n) = \\begin{cases}
124/// 0 & \text{if} \\quad n \leq 0, \\\\
125/// \frac{1}{m} \left ( \frac{m-1}{2m} \right ) ^ {\lfloor \log_2 n \rfloor} &
126/// \\text{otherwise}.
127/// \\end{cases}
128/// $$
129///
130/// The output length is infinite.
131///
132/// # Expected complexity per iteration
133/// $T(n, m) = O(n + m)$
134///
135/// $M(n, m) = O(n / m)$
136///
137/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
138/// `mean_precision_denominator`.
139///
140/// # Panics
141/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
142/// <= mean_bits_denominator`.
143///
144/// # Examples
145/// ```
146/// use malachite_base::iterators::prefix_to_string;
147/// use malachite_base::random::EXAMPLE_SEED;
148/// use malachite_nz::integer::random::random_positive_integers;
149///
150/// assert_eq!(
151/// prefix_to_string(random_positive_integers(EXAMPLE_SEED, 32, 1), 10),
152/// "[22, 4, 178, 55845661150, 93254818, 7577967529619388, 8, 11316951483471, 11, \
153/// 1005760138411689342464923704482, ...]"
154/// )
155/// ```
156pub fn random_positive_integers(
157 seed: Seed,
158 mean_bits_numerator: u64,
159 mean_bits_denominator: u64,
160) -> RandomIntegers<GeometricRandomNaturalValues<i64>> {
161 RandomIntegers {
162 bits: geometric_random_positive_signeds(
163 seed.fork("bits"),
164 mean_bits_numerator,
165 mean_bits_denominator,
166 ),
167 limbs: random_primitive_ints(seed.fork("limbs")),
168 }
169}
170
171/// Generates random negative [`Integer`]s whose absolute values have a specified mean bit length.
172///
173/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
174/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 1. Then an [`Integer`]
175/// is chosen uniformly among all positive [`Integer`]s with that bit length, and negated. The
176/// resulting distribution resembles a negated Pareto distribution. It has no mean or higher-order
177/// statistics (unless $m < 2$, which is not typical).
178///
179/// $$
180/// P(n) = \\begin{cases}
181/// 0 & \text{if} \\quad n \geq 0 ,\\\\
182/// \frac{1}{m} \left ( \frac{m-1}{2m} \right ) ^ {\lfloor \log_2 (-n) \rfloor}
183/// & \\text{otherwise}.
184/// \\end{cases}
185/// $$
186///
187/// The output length is infinite.
188///
189/// # Expected complexity per iteration
190/// $T(n, m) = O(n + m)$
191///
192/// $M(n, m) = O(n / m)$
193///
194/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
195/// `mean_precision_denominator`.
196///
197/// # Panics
198/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
199/// <= mean_bits_denominator`.
200///
201/// # Examples
202/// ```
203/// use malachite_base::iterators::prefix_to_string;
204/// use malachite_base::random::EXAMPLE_SEED;
205/// use malachite_nz::integer::random::random_negative_integers;
206///
207/// assert_eq!(
208/// prefix_to_string(random_negative_integers(EXAMPLE_SEED, 32, 1), 10),
209/// "[-22, -4, -178, -55845661150, -93254818, -7577967529619388, -8, -11316951483471, -11, \
210/// -1005760138411689342464923704482, ...]"
211/// )
212/// ```
213pub fn random_negative_integers(
214 seed: Seed,
215 mean_bits_numerator: u64,
216 mean_bits_denominator: u64,
217) -> RandomIntegers<GeometricRandomNegativeSigneds<i64>> {
218 RandomIntegers {
219 bits: geometric_random_negative_signeds(
220 seed.fork("bits"),
221 mean_bits_numerator,
222 mean_bits_denominator,
223 ),
224 limbs: random_primitive_ints(seed.fork("limbs")),
225 }
226}
227
228/// Generates random nonzero [`Integer`]s whose absolute values have a specified mean bit length.
229///
230/// The actual signed bit length is chosen from a distribution that produces values whose mean
231/// absolute values are $m$, where $m$ is `mean_bits_numerator / mean_bits_denominator` (see
232/// [`geometric_random_nonzero_signeds`]); $m$ must be greater than 1. Then an [`Integer`] is chosen
233/// uniformly among all positive [`Integer`]s with that bit length, and its sign is set to the sign
234/// of the signed bit length. The resulting distribution has no mean or higher-order statistics
235/// (unless $m < 2$, which is not typical).
236///
237/// $$
238/// P(n) = \\begin{cases}
239/// 0 & \text{if} \\quad n = 0, \\\\
240/// \\frac{1}{2m} \\left ( \\frac{m-1}{2m} \\right ) ^ {\\lfloor \\log_2 |n| \\rfloor}
241/// & \\text{otherwise}.
242/// \\end{cases}
243/// $$
244///
245/// The output length is infinite.
246///
247/// # Expected complexity per iteration
248/// $T(n, m) = O(n + m)$
249///
250/// $M(n, m) = O(n / m)$
251///
252/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
253/// `mean_precision_denominator`.
254///
255/// # Panics
256/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
257/// <= mean_bits_denominator`.
258///
259/// # Examples
260/// ```
261/// use malachite_base::iterators::prefix_to_string;
262/// use malachite_base::random::EXAMPLE_SEED;
263/// use malachite_nz::integer::random::random_nonzero_integers;
264///
265/// assert_eq!(
266/// prefix_to_string(random_nonzero_integers(EXAMPLE_SEED, 32, 1), 10),
267/// "[6, 373973144, 46887963477285686350042496363292819122, -93254818, -126908, \
268/// -4471675267836600, 1860142159, -118004986915853475, -98, 346513, ...]"
269/// )
270/// ```
271pub fn random_nonzero_integers(
272 seed: Seed,
273 mean_bits_numerator: u64,
274 mean_bits_denominator: u64,
275) -> RandomIntegers<GeometricRandomNonzeroSigneds<i64>> {
276 RandomIntegers {
277 bits: geometric_random_nonzero_signeds(
278 seed.fork("bits"),
279 mean_bits_numerator,
280 mean_bits_denominator,
281 ),
282 limbs: random_primitive_ints(seed.fork("limbs")),
283 }
284}
285
286/// Generates random [`Integer`]s whose absolute values have a specified mean bit length.
287///
288/// The actual signed bit length is chosen from a distribution that produces values whose mean
289/// absolute values are $m$, where $m$ is `mean_bits_numerator / mean_bits_denominator` (see
290/// [`geometric_random_signeds`]); $m$ must be greater than 0. Then an [`Integer`] is chosen
291/// uniformly among all [`Integer`]s with that bit length, and its sign is set to the sign of the
292/// signed bit length. The resulting distribution has no mean or higher-order statistics (unless $m
293/// < 1$, which is not typical).
294///
295/// $$
296/// P(n) = \\begin{cases}
297/// \\frac{1}{2m+1} & \text{if} \\quad n = 0, \\\\
298/// \\frac{2}{2m+1} \\left ( \\frac{m}{2(m+1)} \\right ) ^ {\\lfloor \\log_2 |n| \\rfloor + 1}
299/// & \\text{otherwise}.
300/// \\end{cases}
301/// $$
302///
303/// The output length is infinite.
304///
305/// # Expected complexity per iteration
306/// $T(n, m) = O(n + m)$
307///
308/// $M(n, m) = O(n / m)$
309///
310/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
311/// `mean_precision_denominator`.
312///
313/// # Panics
314/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, or, if after being reduced
315/// to lowest terms, their sum is greater than or equal to $2^{64}$.
316///
317/// # Examples
318/// ```
319/// use malachite_base::iterators::prefix_to_string;
320/// use malachite_base::random::EXAMPLE_SEED;
321/// use malachite_nz::integer::random::random_integers;
322///
323/// assert_eq!(
324/// prefix_to_string(random_integers(EXAMPLE_SEED, 32, 1), 10),
325/// "[89270, 69403499476962893258904, 62, -1848070042786, -64671510460, -696, 0, -79, 70819, \
326/// 7330, ...]"
327/// )
328/// ```
329pub fn random_integers(
330 seed: Seed,
331 mean_bits_numerator: u64,
332 mean_bits_denominator: u64,
333) -> RandomIntegers<GeometricRandomSigneds<i64>> {
334 RandomIntegers {
335 bits: geometric_random_signeds(
336 seed.fork("bits"),
337 mean_bits_numerator,
338 mean_bits_denominator,
339 ),
340 limbs: random_primitive_ints(seed.fork("limbs")),
341 }
342}
343
344/// Generates striped random [`Integer`]s, given an iterator of random signed bit lengths.
345///
346/// The [`Integer`]s signs are taken from the signs of the bit lengths.
347#[derive(Clone, Debug)]
348pub struct StripedRandomIntegers<I: Iterator<Item = i64>> {
349 bits: I,
350 bit_source: StripedBitSource,
351}
352
353impl<I: Iterator<Item = i64>> Iterator for StripedRandomIntegers<I> {
354 type Item = Integer;
355
356 fn next(&mut self) -> Option<Integer> {
357 let bits = self.bits.next().unwrap();
358 Some(Integer::from_sign_and_abs(
359 bits >= 0,
360 get_striped_random_natural_with_bits(&mut self.bit_source, bits.unsigned_abs()),
361 ))
362 }
363}
364
365/// Generates striped random natural (non-negative) [`Integer`]s with a specified mean bit length.
366///
367/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
368/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 0. A striped bit
369/// sequence with the given stripe parameter is generated and truncated at the bit length. The
370/// highest bit is forced to be 1, and the [`Integer`] is generated from the sequence.
371///
372/// The output length is infinite.
373///
374/// See [`StripedBitSource`] for information about generating striped random numbers.
375///
376/// # Expected complexity per iteration
377/// $T(n, m) = O(n + m)$
378///
379/// $M(n, m) = O(n / m)$
380///
381/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
382/// `mean_precision_denominator`.
383///
384/// # Panics
385/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
386/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or, if
387/// after being reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
388///
389/// # Examples
390/// ```
391/// use malachite_base::iterators::prefix_to_string;
392/// use malachite_base::random::EXAMPLE_SEED;
393/// use malachite_nz::integer::random::striped_random_natural_integers;
394///
395/// assert_eq!(
396/// prefix_to_string(
397/// striped_random_natural_integers(EXAMPLE_SEED, 16, 1, 32, 1),
398/// 10
399/// ),
400/// "[18014656207519744, 2228160, 64, 17592184995840, 1179440951012584587264, \
401/// 9007749010526207, 67108864, 5, 24, 34359738879, ...]"
402/// )
403/// ```
404pub fn striped_random_natural_integers(
405 seed: Seed,
406 mean_stripe_numerator: u64,
407 mean_stripe_denominator: u64,
408 mean_bits_numerator: u64,
409 mean_bits_denominator: u64,
410) -> StripedRandomIntegers<GeometricRandomNaturalValues<i64>> {
411 StripedRandomIntegers {
412 bits: geometric_random_natural_signeds(
413 seed.fork("bits"),
414 mean_bits_numerator,
415 mean_bits_denominator,
416 ),
417 bit_source: StripedBitSource::new(
418 seed.fork("bit_source"),
419 mean_stripe_numerator,
420 mean_stripe_denominator,
421 ),
422 }
423}
424
425/// Generates striped random positive [`Integer`]s with a specified mean bit length.
426///
427/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
428/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 1. A striped bit
429/// sequence with the given stripe parameter is generated and truncated at the bit length. The
430/// highest bit is forced to be 1, and the [`Integer`] is generated from the sequence.
431///
432/// The output length is infinite.
433///
434/// See [`StripedBitSource`] for information about generating striped random numbers.
435///
436/// # Expected complexity per iteration
437/// $T(n, m) = O(n + m)$
438///
439/// $M(n, m) = O(n / m)$
440///
441/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
442/// `mean_precision_denominator`.
443///
444/// # Panics
445/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
446/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
447/// `mean_bits_numerator <= mean_bits_denominator`.
448///
449/// # Examples
450/// ```
451/// use malachite_base::iterators::prefix_to_string;
452/// use malachite_base::random::EXAMPLE_SEED;
453/// use malachite_nz::integer::random::striped_random_positive_integers;
454///
455/// assert_eq!(
456/// prefix_to_string(
457/// striped_random_positive_integers(EXAMPLE_SEED, 16, 1, 32, 1),
458/// 10
459/// ),
460/// "[16, 4, 128, 34391195648, 75493376, 9007199120523391, 8, 8796094070783, 8, \
461/// 950737950171027935941967741439, ...]"
462/// )
463/// ```
464pub fn striped_random_positive_integers(
465 seed: Seed,
466 mean_stripe_numerator: u64,
467 mean_stripe_denominator: u64,
468 mean_bits_numerator: u64,
469 mean_bits_denominator: u64,
470) -> StripedRandomIntegers<GeometricRandomNaturalValues<i64>> {
471 StripedRandomIntegers {
472 bits: geometric_random_positive_signeds(
473 seed.fork("bits"),
474 mean_bits_numerator,
475 mean_bits_denominator,
476 ),
477 bit_source: StripedBitSource::new(
478 seed.fork("bit_source"),
479 mean_stripe_numerator,
480 mean_stripe_denominator,
481 ),
482 }
483}
484
485/// Generates striped random negative [`Integer`]s whose absolute values have a specified mean bit
486/// length.
487///
488/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
489/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 1. A striped bit
490/// sequence with the given stripe parameter is generated and truncated at the bit length. The
491/// highest bit is forced to be 1, and the [`Integer`] is generated from the sequence and negated.
492///
493/// The output length is infinite.
494///
495/// See [`StripedBitSource`] for information about generating striped random numbers.
496///
497/// # Expected complexity per iteration
498/// $T(n, m) = O(n + m)$
499///
500/// $M(n, m) = O(n / m)$
501///
502/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
503/// `mean_precision_denominator`.
504///
505/// # Panics
506/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
507/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
508/// `mean_bits_numerator <= mean_bits_denominator`.
509///
510/// # Examples
511/// ```
512/// use malachite_base::iterators::prefix_to_string;
513/// use malachite_base::random::EXAMPLE_SEED;
514/// use malachite_nz::integer::random::striped_random_negative_integers;
515///
516/// assert_eq!(
517/// prefix_to_string(
518/// striped_random_negative_integers(EXAMPLE_SEED, 16, 1, 32, 1),
519/// 10
520/// ),
521/// "[-16, -4, -128, -34391195648, -75493376, -9007199120523391, -8, -8796094070783, -8, \
522/// -950737950171027935941967741439, ...]"
523/// )
524/// ```
525pub fn striped_random_negative_integers(
526 seed: Seed,
527 mean_stripe_numerator: u64,
528 mean_stripe_denominator: u64,
529 mean_bits_numerator: u64,
530 mean_bits_denominator: u64,
531) -> StripedRandomIntegers<GeometricRandomNegativeSigneds<i64>> {
532 StripedRandomIntegers {
533 bits: geometric_random_negative_signeds(
534 seed.fork("bits"),
535 mean_bits_numerator,
536 mean_bits_denominator,
537 ),
538 bit_source: StripedBitSource::new(
539 seed.fork("bit_source"),
540 mean_stripe_numerator,
541 mean_stripe_denominator,
542 ),
543 }
544}
545
546/// Generates striped random nonzero [`Integer`]s whose absolute values have a specified mean bit
547/// length.
548///
549/// The actual signed bit length is chosen from a distribution that produces values whose mean
550/// absolute values are $m$, where $m$ is `mean_bits_numerator / mean_bits_denominator` (see
551/// [`geometric_random_nonzero_signeds`]); $m$ must be greater than 1. A striped bit sequence with
552/// the given stripe parameter is generated and truncated at the bit length. The highest bit is
553/// forced to be 1, an [`Integer`] is generated from the sequence, and its sign is set to the sign
554/// of the signed bit length. The resulting distribution has no mean or higher-order statistics
555/// (unless $m < 2$, which is not typical).
556///
557/// The output length is infinite.
558///
559/// See [`StripedBitSource`] for information about generating striped random numbers.
560///
561/// # Expected complexity per iteration
562/// $T(n, m) = O(n + m)$
563///
564/// $M(n, m) = O(n / m)$
565///
566/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
567/// `mean_precision_denominator`.
568///
569/// # Panics
570/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
571/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
572/// `mean_bits_numerator <= mean_bits_denominator`.
573///
574/// # Examples
575/// ```
576/// use malachite_base::iterators::prefix_to_string;
577/// use malachite_base::random::EXAMPLE_SEED;
578/// use malachite_nz::integer::random::striped_random_nonzero_integers;
579///
580/// assert_eq!(
581/// prefix_to_string(
582/// striped_random_nonzero_integers(EXAMPLE_SEED, 16, 1, 32, 1),
583/// 10
584/// ),
585/// "[4, 268435456, 84405977732342160290572740160760316144, -133169152, -131064, \
586/// -2251834173421823, 1577058304, -126100789566374399, -76, 270335, ...]"
587/// )
588/// ```
589pub fn striped_random_nonzero_integers(
590 seed: Seed,
591 mean_stripe_numerator: u64,
592 mean_stripe_denominator: u64,
593 mean_bits_numerator: u64,
594 mean_bits_denominator: u64,
595) -> StripedRandomIntegers<GeometricRandomNonzeroSigneds<i64>> {
596 StripedRandomIntegers {
597 bits: geometric_random_nonzero_signeds(
598 seed.fork("bits"),
599 mean_bits_numerator,
600 mean_bits_denominator,
601 ),
602 bit_source: StripedBitSource::new(
603 seed.fork("bit_source"),
604 mean_stripe_numerator,
605 mean_stripe_denominator,
606 ),
607 }
608}
609
610/// Generates striped random [`Integer`]s whose absolute values have a specified mean bit length.
611///
612/// The actual signed bit length is chosen from a distribution that produces values whose mean
613/// absolute values are $m$, where $m$ is `mean_bits_numerator / mean_bits_denominator` (see
614/// [`geometric_random_signeds`]); $m$ must be greater than 0. A striped bit sequence with the given
615/// stripe parameter is generated and truncated at the bit length. The highest bit is forced to be
616/// 1, an [`Integer`] is generated from the sequence, and its sign is set to the sign of the signed
617/// bit length. The resulting distribution has no mean or higher-order statistics (unless $m < 1$,
618/// which is not typical).
619///
620/// The output length is infinite.
621///
622/// See [`StripedBitSource`] for information about generating striped random numbers.
623///
624/// # Expected complexity per iteration
625/// $T(n, m) = O(n + m)$
626///
627/// $M(n, m) = O(n / m)$
628///
629/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
630/// `mean_precision_denominator`.
631///
632/// # Panics
633/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
634/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or, if
635/// after being reduced to lowest terms, their sum is greater than or equal to $2^{64}$.
636///
637/// # Examples
638/// ```
639/// use malachite_base::iterators::prefix_to_string;
640/// use malachite_base::random::EXAMPLE_SEED;
641/// use malachite_nz::integer::random::striped_random_integers;
642///
643/// assert_eq!(
644/// prefix_to_string(striped_random_integers(EXAMPLE_SEED, 16, 1, 32, 1), 10),
645/// "[65536, 75521006248971741167616, 32, -2199023255520, -68719468544, -527, 0, -112, \
646/// 131071, 4152, ...]"
647/// )
648/// ```
649pub fn striped_random_integers(
650 seed: Seed,
651 mean_stripe_numerator: u64,
652 mean_stripe_denominator: u64,
653 mean_bits_numerator: u64,
654 mean_bits_denominator: u64,
655) -> StripedRandomIntegers<GeometricRandomSigneds<i64>> {
656 StripedRandomIntegers {
657 bits: geometric_random_signeds(
658 seed.fork("bits"),
659 mean_bits_numerator,
660 mean_bits_denominator,
661 ),
662 bit_source: StripedBitSource::new(
663 seed.fork("bit_source"),
664 mean_stripe_numerator,
665 mean_stripe_denominator,
666 ),
667 }
668}
669
670/// Uniformly generates random [`Integer`]s in an interval.
671#[derive(Clone, Debug)]
672pub struct UniformRandomIntegerRange {
673 xs: RandomNaturalsLessThan,
674 a: Integer,
675}
676
677impl Iterator for UniformRandomIntegerRange {
678 type Item = Integer;
679
680 fn next(&mut self) -> Option<Integer> {
681 self.xs.next().map(|x| &self.a + Integer::from(x))
682 }
683}
684
685/// Uniformly generates random [`Integer`]s in the half-open interval $[a, b)$.
686///
687/// $a$ must be less than $b$.
688///
689/// $$
690/// P(x) = \\begin{cases}
691/// \frac{1}{b-a} & \text{if} \\quad a \leq x < b, \\\\
692/// 0 & \\text{otherwise}.
693/// \\end{cases}
694/// $$
695///
696/// The output length is infinite.
697///
698/// # Expected complexity per iteration
699/// $T(n) = O(n)$
700///
701/// $M(n) = O(n)$
702///
703/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
704/// b.significant_bits())`.
705///
706/// # Panics
707/// Panics if $a \geq b$.
708///
709/// # Examples
710/// ```
711/// use malachite_base::iterators::prefix_to_string;
712/// use malachite_base::random::EXAMPLE_SEED;
713/// use malachite_nz::integer::random::uniform_random_integer_range;
714/// use malachite_nz::integer::Integer;
715///
716/// assert_eq!(
717/// prefix_to_string(
718/// uniform_random_integer_range(EXAMPLE_SEED, Integer::from(-10), Integer::from(100)),
719/// 10
720/// ),
721/// "[77, 83, -3, 95, 94, 97, 74, 17, 36, 83, ...]"
722/// )
723/// ```
724pub fn uniform_random_integer_range(
725 seed: Seed,
726 a: Integer,
727 b: Integer,
728) -> UniformRandomIntegerRange {
729 assert!(a < b);
730 UniformRandomIntegerRange {
731 xs: random_naturals_less_than(seed, Natural::exact_from(b - &a)),
732 a,
733 }
734}
735
736/// Uniformly generates random [`Integer`]s in the closed interval $[a, b]$.
737///
738/// $a$ must be less than or equal to $b$.
739///
740/// $$
741/// P(x) = \\begin{cases}
742/// \frac{1}{b-a+1} & \text{if} \\quad a \leq x \leq b, \\\\
743/// 0 & \\text{otherwise}.
744/// \\end{cases}
745/// $$
746///
747/// The output length is infinite.
748///
749/// # Expected complexity per iteration
750/// $T(n) = O(n)$
751///
752/// $M(n) = O(n)$
753///
754/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
755/// b.significant_bits())`.
756///
757/// # Panics
758/// Panics if $a > b$.
759///
760/// # Examples
761/// ```
762/// use malachite_base::iterators::prefix_to_string;
763/// use malachite_base::random::EXAMPLE_SEED;
764/// use malachite_nz::integer::random::uniform_random_integer_inclusive_range;
765/// use malachite_nz::integer::Integer;
766///
767/// assert_eq!(
768/// prefix_to_string(
769/// uniform_random_integer_inclusive_range(
770/// EXAMPLE_SEED,
771/// Integer::from(-10),
772/// Integer::from(100)
773/// ),
774/// 10
775/// ),
776/// "[77, 83, -3, 95, 94, 97, 74, 17, 36, 83, ...]"
777/// )
778/// ```
779#[inline]
780pub fn uniform_random_integer_inclusive_range(
781 seed: Seed,
782 a: Integer,
783 b: Integer,
784) -> UniformRandomIntegerRange {
785 assert!(a <= b);
786 uniform_random_integer_range(seed, a, b + Integer::ONE)
787}
788
789/// Generates a random [`Integer`] in the half-open interval $[a, b)$.
790///
791/// The [`Integer`] is chosen uniformly from the interval.
792///
793/// $$
794/// P(n) = \\begin{cases}
795/// 1/(b-a) & \text{if} a\leq n<b, \\\\
796/// 0 & \\text{otherwise},
797/// \\end{cases}
798/// $$
799/// where $\ell$ is `limit`.
800///
801/// # Expected complexity
802/// $T(n) = O(n)$
803///
804/// $M(m) = O(m)$
805///
806/// where $T$ is time, $M$ is additional memory, $n$ is `mean_bits_numerator +
807/// mean_bits_denominator`, and $m$ is `max(a.significant_bits(), b.significant_bits())`.
808///
809/// # Examples
810/// ```
811/// use malachite_base::num::random::random_primitive_ints;
812/// use malachite_base::random::EXAMPLE_SEED;
813/// use malachite_nz::integer::random::get_uniform_random_integer_from_range;
814/// use malachite_nz::integer::Integer;
815///
816/// assert_eq!(
817/// get_uniform_random_integer_from_range(
818/// &mut random_primitive_ints(EXAMPLE_SEED),
819/// Integer::from(500u32),
820/// Integer::from(1000u32)
821/// ),
822/// 869
823/// );
824/// ```
825pub fn get_uniform_random_integer_from_range(
826 limbs: &mut RandomPrimitiveInts<u64>,
827 a: Integer,
828 b: Integer,
829) -> Integer {
830 assert!(a < b);
831 Integer::from(get_random_natural_less_than(
832 limbs,
833 &Natural::exact_from(b - &a),
834 )) + a
835}
836
837/// Generates a random [`Integer`] in the closed interval $[a, b]$.
838///
839/// The [`Integer`] is chosen uniformly from the interval.
840///
841/// $$
842/// P(n) = \\begin{cases}
843/// 1/(b-a+1) & \text{if} a\leq n\leq b, \\\\
844/// 0 & \\text{otherwise},
845/// \\end{cases}
846/// $$
847/// where $\ell$ is `limit`.
848///
849/// # Expected complexity
850/// $T(n) = O(n)$
851///
852/// $M(m) = O(m)$
853///
854/// where $T$ is time, $M$ is additional memory, $n$ is `mean_bits_numerator +
855/// mean_bits_denominator`, and $m$ is `max(a.significant_bits(), b.significant_bits())`.
856///
857/// # Examples
858/// ```
859/// use malachite_base::num::random::random_primitive_ints;
860/// use malachite_base::random::EXAMPLE_SEED;
861/// use malachite_nz::integer::random::get_uniform_random_integer_from_inclusive_range;
862/// use malachite_nz::integer::Integer;
863///
864/// assert_eq!(
865/// get_uniform_random_integer_from_inclusive_range(
866/// &mut random_primitive_ints(EXAMPLE_SEED),
867/// Integer::from(500u32),
868/// Integer::from(1001u32)
869/// ),
870/// 869
871/// );
872/// ```
873pub fn get_uniform_random_integer_from_inclusive_range(
874 limbs: &mut RandomPrimitiveInts<u64>,
875 a: Integer,
876 b: Integer,
877) -> Integer {
878 assert!(a <= b);
879 get_uniform_random_integer_from_range(limbs, a, b + Integer::ONE)
880}
881
882fn signed_significant_bits(a: &Integer) -> (u64, i64) {
883 let unsigned_bits = a.significant_bits();
884 let bits = if *a >= 0 {
885 i64::exact_from(unsigned_bits)
886 } else {
887 -i64::exact_from(unsigned_bits)
888 };
889 (unsigned_bits, bits)
890}
891
892fn signed_min_bit_range(
893 seed: Seed,
894 a: Integer,
895 unsigned_min_bits: u64,
896) -> UniformRandomIntegerRange {
897 if a >= 0 {
898 uniform_random_integer_range(seed, a, Integer::power_of_2(unsigned_min_bits))
899 } else {
900 uniform_random_integer_inclusive_range(seed, a, -Integer::power_of_2(unsigned_min_bits - 1))
901 }
902}
903
904fn signed_max_bit_range(
905 seed: Seed,
906 a: Integer,
907 unsigned_max_bits: u64,
908) -> UniformRandomIntegerRange {
909 if a > 0 {
910 uniform_random_integer_inclusive_range(seed, Integer::power_of_2(unsigned_max_bits - 1), a)
911 } else {
912 // also handles a == 0
913 uniform_random_integer_inclusive_range(
914 seed,
915 -Integer::power_of_2(unsigned_max_bits) + Integer::ONE,
916 a,
917 )
918 }
919}
920
921fn get_random_integer_from_signed_min_bit_range(
922 limbs: &mut RandomPrimitiveInts<u64>,
923 a: Integer,
924 unsigned_min_bits: u64,
925) -> Integer {
926 if a >= 0 {
927 get_uniform_random_integer_from_range(limbs, a, Integer::power_of_2(unsigned_min_bits))
928 } else {
929 get_uniform_random_integer_from_inclusive_range(
930 limbs,
931 a,
932 -Integer::power_of_2(unsigned_min_bits - 1),
933 )
934 }
935}
936
937fn get_random_integer_from_signed_max_bit_range(
938 limbs: &mut RandomPrimitiveInts<u64>,
939 a: Integer,
940 unsigned_max_bits: u64,
941) -> Integer {
942 if a > 0 {
943 get_uniform_random_integer_from_inclusive_range(
944 limbs,
945 Integer::power_of_2(unsigned_max_bits - 1),
946 a,
947 )
948 } else {
949 // also handles a == 0
950 get_uniform_random_integer_from_inclusive_range(
951 limbs,
952 -Integer::power_of_2(unsigned_max_bits) + Integer::ONE,
953 a,
954 )
955 }
956}
957
958fn get_striped_random_integer_from_signed_min_bit_range(
959 xs: &mut StripedBitSource,
960 range_generator: &mut VariableRangeGenerator,
961 a: Integer,
962 unsigned_min_bits: u64,
963) -> Integer {
964 if a >= 0 {
965 get_striped_random_integer_from_range(
966 xs,
967 range_generator,
968 a,
969 Integer::power_of_2(unsigned_min_bits),
970 )
971 } else {
972 get_striped_random_integer_from_inclusive_range(
973 xs,
974 range_generator,
975 a,
976 -Integer::power_of_2(unsigned_min_bits - 1),
977 )
978 }
979}
980
981fn get_striped_random_integer_from_signed_max_bit_range(
982 xs: &mut StripedBitSource,
983 range_generator: &mut VariableRangeGenerator,
984 a: Integer,
985 unsigned_max_bits: u64,
986) -> Integer {
987 if a > 0 {
988 get_striped_random_integer_from_inclusive_range(
989 xs,
990 range_generator,
991 Integer::power_of_2(unsigned_max_bits - 1),
992 a,
993 )
994 } else {
995 // also handles a == 0
996 get_striped_random_integer_from_inclusive_range(
997 xs,
998 range_generator,
999 -Integer::power_of_2(unsigned_max_bits) + Integer::ONE,
1000 a,
1001 )
1002 }
1003}
1004
1005/// Generates random [`Integer`]s greater than or equal to a lower bound, or less than or equal to
1006/// an upper bound.
1007#[derive(Clone, Debug)]
1008pub struct RandomIntegerRangeToInfinity {
1009 boundary_bits: i64,
1010 bits: GeometricRandomSignedRange<i64>,
1011 limbs: RandomPrimitiveInts<u64>,
1012 boundary_bit_xs: UniformRandomIntegerRange,
1013}
1014
1015impl Iterator for RandomIntegerRangeToInfinity {
1016 type Item = Integer;
1017
1018 fn next(&mut self) -> Option<Integer> {
1019 let bits = self.bits.next().unwrap();
1020 if bits == self.boundary_bits {
1021 self.boundary_bit_xs.next()
1022 } else {
1023 Some(Integer::from_sign_and_abs(
1024 bits >= 0,
1025 get_random_natural_with_bits(&mut self.limbs, bits.unsigned_abs()),
1026 ))
1027 }
1028 }
1029}
1030
1031/// Generates random [`Integer`]s greater than or equal to a lower bound $a$.
1032///
1033/// The mean bit length $m$ of the absolute values of the generated values is specified. $m$ is
1034/// equal to `mean_bits_numerator / mean_bits_denominator`.
1035///
1036/// The output length is infinite.
1037///
1038/// # Expected complexity per iteration
1039/// $T(n, m) = O(n + m)$
1040///
1041/// $M(n, m) = O(n / m)$
1042///
1043/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1044/// `mean_precision_denominator`.
1045///
1046/// # Panics
1047/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a > 0$ and their ratio
1048/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1049/// leads to arithmetic overflow.
1050///
1051/// # Examples
1052/// ```
1053/// use malachite_base::iterators::prefix_to_string;
1054/// use malachite_base::random::EXAMPLE_SEED;
1055/// use malachite_nz::integer::random::random_integer_range_to_infinity;
1056/// use malachite_nz::integer::Integer;
1057///
1058/// assert_eq!(
1059/// prefix_to_string(
1060/// random_integer_range_to_infinity(EXAMPLE_SEED, Integer::from(-1000), 10, 1),
1061/// 10
1062/// ),
1063/// "[15542, 2, 1714, 27863518, -162, 956, 8, 14648399, -419, -98, ...]"
1064/// )
1065/// ```
1066pub fn random_integer_range_to_infinity(
1067 seed: Seed,
1068 a: Integer,
1069 mean_bits_numerator: u64,
1070 mean_bits_denominator: u64,
1071) -> RandomIntegerRangeToInfinity {
1072 let (unsigned_min_bits, min_bits) = signed_significant_bits(&a);
1073 RandomIntegerRangeToInfinity {
1074 boundary_bits: min_bits,
1075 bits: geometric_random_signed_inclusive_range(
1076 seed.fork("bits"),
1077 min_bits,
1078 i64::MAX,
1079 mean_bits_numerator,
1080 mean_bits_denominator,
1081 ),
1082 limbs: random_primitive_ints(seed.fork("limbs")),
1083 boundary_bit_xs: signed_min_bit_range(seed.fork("min_bit_xs"), a, unsigned_min_bits),
1084 }
1085}
1086
1087/// Generates a random [`Integer`] greater than or equal to a lower bound $a$.
1088///
1089/// The mean bit length $m$ of the absolute values of the generated value is specified. $m$ is equal
1090/// to `mean_bits_numerator / mean_bits_denominator`.
1091///
1092/// # Expected complexity
1093/// $T(n, m) = O(n + m)$
1094///
1095/// $M(n, m) = O(n / m)$
1096///
1097/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1098/// `mean_precision_denominator`.
1099///
1100/// # Panics
1101/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a > 0$ and their ratio
1102/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1103/// leads to arithmetic overflow.
1104///
1105/// # Examples
1106/// ```
1107/// use malachite_base::num::random::random_primitive_ints;
1108/// use malachite_base::num::random::VariableRangeGenerator;
1109/// use malachite_base::random::EXAMPLE_SEED;
1110/// use malachite_nz::integer::random::get_random_integer_from_range_to_infinity;
1111/// use malachite_nz::integer::Integer;
1112///
1113/// assert_eq!(
1114/// get_random_integer_from_range_to_infinity(
1115/// &mut random_primitive_ints(EXAMPLE_SEED.fork("limbs")),
1116/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1117/// Integer::from(-1000),
1118/// 20,
1119/// 1
1120/// ),
1121/// -2
1122/// )
1123/// ```
1124pub fn get_random_integer_from_range_to_infinity(
1125 limbs: &mut RandomPrimitiveInts<u64>,
1126 range_generator: &mut VariableRangeGenerator,
1127 a: Integer,
1128 mean_bits_numerator: u64,
1129 mean_bits_denominator: u64,
1130) -> Integer {
1131 let (unsigned_min_bits, min_bits) = signed_significant_bits(&a);
1132 let bits = get_geometric_random_signed_from_inclusive_range(
1133 range_generator,
1134 min_bits,
1135 i64::MAX,
1136 mean_bits_numerator,
1137 mean_bits_denominator,
1138 );
1139 if bits == min_bits {
1140 get_random_integer_from_signed_min_bit_range(limbs, a, unsigned_min_bits)
1141 } else {
1142 Integer::from_sign_and_abs(
1143 bits >= 0,
1144 get_random_natural_with_bits(limbs, bits.unsigned_abs()),
1145 )
1146 }
1147}
1148
1149/// Generates random [`Integer`]s less than or equal to an upper bound $a$.
1150///
1151/// The mean bit length $m$ of the absolute values of the generated values is specified. $m$ is
1152/// equal to `mean_bits_numerator / mean_bits_denominator`.
1153///
1154/// The output length is infinite.
1155///
1156/// # Expected complexity per iteration
1157/// $T(n, m) = O(n + m)$
1158///
1159/// $M(n, m) = O(n / m)$
1160///
1161/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1162/// `mean_precision_denominator`.
1163///
1164/// # Panics
1165/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a < 0$ and their ratio
1166/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1167/// leads to arithmetic overflow.
1168///
1169/// # Examples
1170/// ```
1171/// use malachite_base::iterators::prefix_to_string;
1172/// use malachite_base::random::EXAMPLE_SEED;
1173/// use malachite_nz::integer::random::random_integer_range_to_negative_infinity;
1174/// use malachite_nz::integer::Integer;
1175///
1176/// assert_eq!(
1177/// prefix_to_string(
1178/// random_integer_range_to_negative_infinity(EXAMPLE_SEED, Integer::from(1000), 10, 1),
1179/// 10
1180/// ),
1181/// "[6, 2, -1714, -235958584061012446, -455842, 514, -12, -14936760, 335, 99, ...]"
1182/// )
1183/// ```
1184pub fn random_integer_range_to_negative_infinity(
1185 seed: Seed,
1186 a: Integer,
1187 mean_bits_numerator: u64,
1188 mean_bits_denominator: u64,
1189) -> RandomIntegerRangeToInfinity {
1190 let (unsigned_max_bits, max_bits) = signed_significant_bits(&a);
1191 RandomIntegerRangeToInfinity {
1192 boundary_bits: max_bits,
1193 bits: geometric_random_signed_inclusive_range(
1194 seed.fork("bits"),
1195 i64::MIN,
1196 max_bits,
1197 mean_bits_numerator,
1198 mean_bits_denominator,
1199 ),
1200 limbs: random_primitive_ints(seed.fork("limbs")),
1201 boundary_bit_xs: signed_max_bit_range(seed.fork("max_bit_xs"), a, unsigned_max_bits),
1202 }
1203}
1204
1205/// Generates a random [`Integer`] less than or equal to a lower bound $a$.
1206///
1207/// The mean bit length $m$ of the absolute values of the generated value is specified. $m$ is equal
1208/// to `mean_bits_numerator / mean_bits_denominator`.
1209///
1210/// # Expected complexity
1211/// $T(n, m) = O(n + m)$
1212///
1213/// $M(n, m) = O(n / m)$
1214///
1215/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1216/// `mean_precision_denominator`.
1217///
1218/// # Panics
1219/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a < 0$ and their ratio
1220/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1221/// leads to arithmetic overflow.
1222///
1223/// # Examples
1224/// ```
1225/// use malachite_base::num::random::random_primitive_ints;
1226/// use malachite_base::num::random::VariableRangeGenerator;
1227/// use malachite_base::random::EXAMPLE_SEED;
1228/// use malachite_nz::integer::random::get_random_integer_from_range_to_negative_infinity;
1229/// use malachite_nz::integer::Integer;
1230///
1231/// assert_eq!(
1232/// get_random_integer_from_range_to_negative_infinity(
1233/// &mut random_primitive_ints(EXAMPLE_SEED.fork("limbs")),
1234/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1235/// Integer::from(-1000),
1236/// 20,
1237/// 1
1238/// ),
1239/// -3254
1240/// )
1241/// ```
1242pub fn get_random_integer_from_range_to_negative_infinity(
1243 limbs: &mut RandomPrimitiveInts<u64>,
1244 range_generator: &mut VariableRangeGenerator,
1245 a: Integer,
1246 mean_bits_numerator: u64,
1247 mean_bits_denominator: u64,
1248) -> Integer {
1249 let (unsigned_max_bits, max_bits) = signed_significant_bits(&a);
1250 let bits = get_geometric_random_signed_from_inclusive_range(
1251 range_generator,
1252 i64::MIN,
1253 max_bits,
1254 mean_bits_numerator,
1255 mean_bits_denominator,
1256 );
1257 if bits == max_bits {
1258 get_random_integer_from_signed_max_bit_range(limbs, a, unsigned_max_bits)
1259 } else {
1260 Integer::from_sign_and_abs(
1261 bits >= 0,
1262 get_random_natural_with_bits(limbs, bits.unsigned_abs()),
1263 )
1264 }
1265}
1266
1267#[doc(hidden)]
1268#[derive(Clone, Debug)]
1269pub struct RandomIntegerRangeMultipleOrders {
1270 min_bits: i64,
1271 max_bits: i64,
1272 bits: GeometricRandomSignedRange<i64>,
1273 limbs: RandomPrimitiveInts<u64>,
1274 min_bit_xs: UniformRandomIntegerRange,
1275 max_bit_xs: UniformRandomIntegerRange,
1276}
1277
1278impl Iterator for RandomIntegerRangeMultipleOrders {
1279 type Item = Integer;
1280
1281 fn next(&mut self) -> Option<Integer> {
1282 let bits = self.bits.next().unwrap();
1283 if bits == self.min_bits {
1284 self.min_bit_xs.next()
1285 } else if bits == self.max_bits {
1286 self.max_bit_xs.next()
1287 } else {
1288 Some(Integer::from_sign_and_abs(
1289 bits >= 0,
1290 get_random_natural_with_bits(&mut self.limbs, bits.unsigned_abs()),
1291 ))
1292 }
1293 }
1294}
1295
1296/// Generates random [`Integer`]s in an interval.
1297#[derive(Clone, Debug)]
1298#[allow(clippy::large_enum_variant)]
1299pub enum RandomIntegerRange {
1300 SingleOrder(UniformRandomIntegerRange),
1301 MultipleOrders(RandomIntegerRangeMultipleOrders),
1302}
1303
1304impl Iterator for RandomIntegerRange {
1305 type Item = Integer;
1306
1307 fn next(&mut self) -> Option<Integer> {
1308 match self {
1309 Self::SingleOrder(xs) => xs.next(),
1310 Self::MultipleOrders(xs) => xs.next(),
1311 }
1312 }
1313}
1314
1315/// Generates random [`Integer`]s in the half-open interval $[a, b)$.
1316///
1317/// In general, the [`Integer`]s are not generated uniformly; for that, use
1318/// [`uniform_random_integer_range`]. Instead, [`Integer`]s with smaller bit lengths are generated
1319/// more frequently.
1320///
1321/// The distribution of generated values is parametrized by a number $m$, given by
1322/// `mean_bits_numerator / mean_bits_denominator`. It is not actually the mean bit length, though it
1323/// approaches the mean bit length of the values minus $a$ as $\log (b/a)$ approaches infinity. $m$
1324/// cannot be 0, and must be greater than the bit length of the smallest integer in the range, but
1325/// it may be arbitrarily large. The smaller it is, the more quickly the probabilities decrease as
1326/// bit length increases. The larger it is, the more closely the distribution approaches a uniform
1327/// distribution over the bit lengths.
1328///
1329/// Once a bit length is selected, the [`Integer`] is chosen uniformly from all [`Integer`]s with
1330/// that bit length that are in $[a, b)$.
1331///
1332/// The output length is infinite.
1333///
1334/// # Expected complexity per iteration
1335/// $T(n) = O(n)$
1336///
1337/// $M(m) = O(m)$
1338///
1339/// where $T$ is time, $M$ is additional memory, $n$ is `mean_bits_numerator +
1340/// mean_bits_denominator`, and $m$ is `max(a.significant_bits(), b.significant_bits())`.
1341///
1342/// # Panics
1343/// Panics if $a \geq b$, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if their
1344/// ratio is less than or equal to the bit length of the smallest integer in the range, or if they
1345/// are too large and manipulating them leads to arithmetic overflow.
1346///
1347/// # Examples
1348/// ```
1349/// use malachite_base::iterators::prefix_to_string;
1350/// use malachite_base::random::EXAMPLE_SEED;
1351/// use malachite_nz::integer::random::random_integer_range;
1352/// use malachite_nz::integer::Integer;
1353///
1354/// assert_eq!(
1355/// prefix_to_string(
1356/// random_integer_range(
1357/// EXAMPLE_SEED,
1358/// Integer::from(-1000),
1359/// Integer::from(1000000000),
1360/// 20,
1361/// 1
1362/// ),
1363/// 10
1364/// ),
1365/// "[1, 1728664, 434, -30, 5282, 515436476, 2353848, -15, 19, 418, ...]"
1366/// )
1367/// ```
1368#[inline]
1369pub fn random_integer_range(
1370 seed: Seed,
1371 a: Integer,
1372 b: Integer,
1373 mean_bits_numerator: u64,
1374 mean_bits_denominator: u64,
1375) -> RandomIntegerRange {
1376 assert!(a < b);
1377 random_integer_inclusive_range(
1378 seed,
1379 a,
1380 b - Integer::ONE,
1381 mean_bits_numerator,
1382 mean_bits_denominator,
1383 )
1384}
1385
1386/// Generates random [`Integer`]s in the closed interval $[a, b]$.
1387///
1388/// In general, the [`Integer`]s are not generated uniformly; for that, use
1389/// [`uniform_random_integer_inclusive_range`]. Instead, [`Integer`]s with smaller bit lengths are
1390/// generated more frequently.
1391///
1392/// The distribution of generated values is parametrized by a number $m$, given by
1393/// `mean_bits_numerator / mean_bits_denominator`. It is not actually the mean bit length, though it
1394/// approaches the mean bit length of the values minus $a$ as $\log (b/a)$ approaches infinity. $m$
1395/// cannot be 0, and must be greater than the bit length of the smallest integer in the range, but
1396/// it may be arbitrarily large. The smaller it is, the more quickly the probabilities decrease as
1397/// bit length increases. The larger it is, the more closely the distribution approaches a uniform
1398/// distribution over the bit lengths.
1399///
1400/// Once a bit length is selected, the [`Integer`] is chosen uniformly from all [`Integer`]s with
1401/// that bit length that are in $[a, b]$.
1402///
1403/// The output length is infinite.
1404///
1405/// # Expected complexity per iteration
1406/// $T(n) = O(n)$
1407///
1408/// $M(m) = O(m)$
1409///
1410/// where $T$ is time, $M$ is additional memory, $n$ is `mean_bits_numerator +
1411/// mean_bits_denominator`, and $m$ is `max(a.significant_bits(), b.significant_bits())`.
1412///
1413/// # Panics
1414/// Panics if $a > b$, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if their ratio
1415/// is less than or equal to the bit length of the smallest integer in the range, or if they are too
1416/// large and manipulating them leads to arithmetic overflow.
1417///
1418/// # Examples
1419/// ```
1420/// use malachite_base::iterators::prefix_to_string;
1421/// use malachite_base::random::EXAMPLE_SEED;
1422/// use malachite_nz::integer::random::random_integer_inclusive_range;
1423/// use malachite_nz::integer::Integer;
1424///
1425/// assert_eq!(
1426/// prefix_to_string(
1427/// random_integer_inclusive_range(
1428/// EXAMPLE_SEED,
1429/// Integer::from(-1000),
1430/// Integer::from(999999999),
1431/// 20,
1432/// 1
1433/// ),
1434/// 10
1435/// ),
1436/// "[1, 1728664, 434, -30, 5282, 515436476, 2353848, -15, 19, 418, ...]"
1437/// )
1438/// ```
1439pub fn random_integer_inclusive_range(
1440 seed: Seed,
1441 a: Integer,
1442 b: Integer,
1443 mean_bits_numerator: u64,
1444 mean_bits_denominator: u64,
1445) -> RandomIntegerRange {
1446 assert!(a <= b);
1447 let (unsigned_min_bits, min_bits) = signed_significant_bits(&a);
1448 let (unsigned_max_bits, max_bits) = signed_significant_bits(&b);
1449 if min_bits == max_bits {
1450 RandomIntegerRange::SingleOrder(uniform_random_integer_inclusive_range(seed, a, b))
1451 } else {
1452 RandomIntegerRange::MultipleOrders(RandomIntegerRangeMultipleOrders {
1453 min_bits,
1454 max_bits,
1455 bits: geometric_random_signed_inclusive_range(
1456 seed.fork("bits"),
1457 min_bits,
1458 max_bits,
1459 mean_bits_numerator,
1460 mean_bits_denominator,
1461 ),
1462 limbs: random_primitive_ints(seed.fork("limbs")),
1463 min_bit_xs: signed_min_bit_range(seed.fork("min_bit_xs"), a, unsigned_min_bits),
1464 max_bit_xs: signed_max_bit_range(seed.fork("max_bit_xs"), b, unsigned_max_bits),
1465 })
1466 }
1467}
1468
1469/// Generates random striped [`Integer`]s from a range.
1470#[derive(Clone, Debug)]
1471pub enum StripedRandomIntegerInclusiveRange {
1472 NonNegative(StripedRandomNaturalInclusiveRange),
1473 Negative(StripedRandomNaturalInclusiveRange),
1474 Both(
1475 RandomBools,
1476 Box<StripedRandomNaturalInclusiveRange>,
1477 Box<StripedRandomNaturalInclusiveRange>,
1478 ),
1479}
1480
1481impl Iterator for StripedRandomIntegerInclusiveRange {
1482 type Item = Integer;
1483
1484 fn next(&mut self) -> Option<Integer> {
1485 match self {
1486 Self::NonNegative(xs) => xs.next().map(Integer::from),
1487 Self::Negative(xs) => xs.next().map(|x| Integer::from_sign_and_abs(false, x)),
1488 Self::Both(bs, xs_nn, xs_n) => {
1489 if bs.next().unwrap() {
1490 xs_nn.next().map(Integer::from)
1491 } else {
1492 xs_n.next().map(|x| Integer::from_sign_and_abs(false, x))
1493 }
1494 }
1495 }
1496 }
1497}
1498
1499/// Generates random striped [`Integer`]s in the range $[a, b)$.
1500///
1501/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
1502/// length will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean
1503/// run length.
1504///
1505/// The output length is infinite.
1506///
1507/// See [`StripedBitSource`] for information about generating striped random numbers.
1508///
1509/// # Expected complexity per iteration
1510/// $T(n) = O(n)$
1511///
1512/// $M(n) = O(n)$
1513///
1514/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1515/// b.significant_bits())`.
1516///
1517/// # Panics
1518/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <=
1519/// mean_stripe_denominator`, or if $a \geq b$.
1520///
1521/// # Examples
1522/// ```
1523/// use malachite_base::iterators::prefix_to_string;
1524/// use malachite_base::random::EXAMPLE_SEED;
1525/// use malachite_base::strings::ToBinaryString;
1526/// use malachite_nz::integer::random::striped_random_integer_range;
1527/// use malachite_nz::integer::Integer;
1528///
1529/// assert_eq!(
1530/// prefix_to_string(
1531/// striped_random_integer_range(EXAMPLE_SEED, Integer::from(-4), Integer::from(7), 4, 1)
1532/// .map(|x| x.to_binary_string()),
1533/// 10
1534/// ),
1535/// "[-100, -100, 110, 11, -100, 0, 110, 11, 0, 110, ...]"
1536/// );
1537/// ```
1538#[inline]
1539pub fn striped_random_integer_range(
1540 seed: Seed,
1541 a: Integer,
1542 b: Integer,
1543 mean_stripe_numerator: u64,
1544 mean_stripe_denominator: u64,
1545) -> StripedRandomIntegerInclusiveRange {
1546 assert!(a < b);
1547 striped_random_integer_inclusive_range(
1548 seed,
1549 a,
1550 b - Integer::ONE,
1551 mean_stripe_numerator,
1552 mean_stripe_denominator,
1553 )
1554}
1555
1556/// Generates random striped [`Integer`]s in the range $[a, b]$.
1557///
1558/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
1559/// length will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean
1560/// run length.
1561///
1562/// The output length is infinite.
1563///
1564/// See [`StripedBitSource`] for information about generating striped random numbers.
1565///
1566/// # Expected complexity per iteration
1567/// $T(n) = O(n)$
1568///
1569/// $M(n) = O(n)$
1570///
1571/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1572/// b.significant_bits())`.
1573///
1574/// # Panics
1575/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <=
1576/// mean_stripe_denominator`, or if $a > b$.
1577///
1578/// # Examples
1579/// ```
1580/// use malachite_base::iterators::prefix_to_string;
1581/// use malachite_base::random::EXAMPLE_SEED;
1582/// use malachite_base::strings::ToBinaryString;
1583/// use malachite_nz::integer::random::striped_random_integer_inclusive_range;
1584/// use malachite_nz::integer::Integer;
1585///
1586/// assert_eq!(
1587/// prefix_to_string(
1588/// striped_random_integer_inclusive_range(
1589/// EXAMPLE_SEED,
1590/// Integer::from(-4),
1591/// Integer::from(6),
1592/// 4,
1593/// 1
1594/// )
1595/// .map(|x| x.to_binary_string()),
1596/// 10
1597/// ),
1598/// "[-100, -100, 110, 11, -100, 0, 110, 11, 0, 110, ...]"
1599/// );
1600/// ```
1601pub fn striped_random_integer_inclusive_range(
1602 seed: Seed,
1603 a: Integer,
1604 b: Integer,
1605 mean_stripe_numerator: u64,
1606 mean_stripe_denominator: u64,
1607) -> StripedRandomIntegerInclusiveRange {
1608 assert!(a <= b);
1609 if a >= 0u32 {
1610 StripedRandomIntegerInclusiveRange::NonNegative(striped_random_natural_inclusive_range(
1611 seed,
1612 a.unsigned_abs(),
1613 b.unsigned_abs(),
1614 mean_stripe_numerator,
1615 mean_stripe_denominator,
1616 ))
1617 } else if b < 0u32 {
1618 StripedRandomIntegerInclusiveRange::Negative(striped_random_natural_inclusive_range(
1619 seed,
1620 b.unsigned_abs(),
1621 a.unsigned_abs(),
1622 mean_stripe_numerator,
1623 mean_stripe_denominator,
1624 ))
1625 } else {
1626 StripedRandomIntegerInclusiveRange::Both(
1627 random_bools(seed.fork("sign")),
1628 Box::new(striped_random_natural_inclusive_range(
1629 seed.fork("non-negative"),
1630 Natural::ZERO,
1631 b.unsigned_abs(),
1632 mean_stripe_numerator,
1633 mean_stripe_denominator,
1634 )),
1635 Box::new(striped_random_natural_inclusive_range(
1636 seed.fork("negative"),
1637 Natural::ONE,
1638 a.unsigned_abs(),
1639 mean_stripe_numerator,
1640 mean_stripe_denominator,
1641 )),
1642 )
1643 }
1644}
1645
1646/// Generates a random striped [`Integer`] in the range $[a, b)$.
1647///
1648/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
1649/// will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean run
1650/// length.
1651///
1652/// See [`StripedBitSource`] for information about generating striped random numbers.
1653///
1654/// # Expected complexity
1655/// $T(n) = O(n)$
1656///
1657/// $M(n) = O(n)$
1658///
1659/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1660/// b.significant_bits())`.
1661///
1662/// # Panics
1663/// Panics if $a \geq b$.
1664///
1665/// # Examples
1666/// ```
1667/// use malachite_base::num::random::striped::StripedBitSource;
1668/// use malachite_base::num::random::VariableRangeGenerator;
1669/// use malachite_base::random::EXAMPLE_SEED;
1670/// use malachite_nz::integer::random::get_striped_random_integer_from_range;
1671/// use malachite_nz::integer::Integer;
1672///
1673/// assert_eq!(
1674/// get_striped_random_integer_from_range(
1675/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1),
1676/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1677/// Integer::from(-4),
1678/// Integer::from(7),
1679/// ),
1680/// -4
1681/// );
1682/// ```
1683#[inline]
1684pub fn get_striped_random_integer_from_range(
1685 xs: &mut StripedBitSource,
1686 range_generator: &mut VariableRangeGenerator,
1687 a: Integer,
1688 b: Integer,
1689) -> Integer {
1690 assert!(a < b);
1691 get_striped_random_integer_from_inclusive_range(xs, range_generator, a, b - Integer::ONE)
1692}
1693
1694/// Generates a random striped [`Integer`] in the range $[a, b]$.
1695///
1696/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
1697/// will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean run
1698/// length.
1699///
1700/// See [`StripedBitSource`] for information about generating striped random numbers.
1701///
1702/// # Expected complexity
1703/// $T(n) = O(n)$
1704///
1705/// $M(n) = O(n)$
1706///
1707/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1708/// b.significant_bits())`.
1709///
1710/// # Panics
1711/// Panics if $a > b$.
1712///
1713/// # Examples
1714/// ```
1715/// use malachite_base::num::random::striped::StripedBitSource;
1716/// use malachite_base::num::random::VariableRangeGenerator;
1717/// use malachite_base::random::EXAMPLE_SEED;
1718/// use malachite_nz::integer::random::get_striped_random_integer_from_inclusive_range;
1719/// use malachite_nz::integer::Integer;
1720///
1721/// assert_eq!(
1722/// get_striped_random_integer_from_inclusive_range(
1723/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1),
1724/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1725/// Integer::from(-4),
1726/// Integer::from(7),
1727/// ),
1728/// -4
1729/// );
1730/// ```
1731pub fn get_striped_random_integer_from_inclusive_range(
1732 xs: &mut StripedBitSource,
1733 range_generator: &mut VariableRangeGenerator,
1734 a: Integer,
1735 b: Integer,
1736) -> Integer {
1737 assert!(a <= b);
1738 if a >= 0u32 {
1739 Integer::from(get_striped_random_natural_from_inclusive_range(
1740 xs,
1741 a.unsigned_abs(),
1742 b.unsigned_abs(),
1743 ))
1744 } else if b < 0u32 {
1745 Integer::from_sign_and_abs(
1746 false,
1747 get_striped_random_natural_from_inclusive_range(xs, b.unsigned_abs(), a.unsigned_abs()),
1748 )
1749 } else if range_generator.next_bool() {
1750 Integer::from(get_striped_random_natural_from_inclusive_range(
1751 xs,
1752 Natural::ZERO,
1753 b.unsigned_abs(),
1754 ))
1755 } else {
1756 Integer::from_sign_and_abs(
1757 false,
1758 get_striped_random_natural_from_inclusive_range(xs, Natural::ONE, a.unsigned_abs()),
1759 )
1760 }
1761}
1762
1763fn striped_signed_min_bit_range(
1764 seed: Seed,
1765 a: Integer,
1766 unsigned_min_bits: u64,
1767 mean_stripe_numerator: u64,
1768 mean_stripe_denominator: u64,
1769) -> StripedRandomIntegerInclusiveRange {
1770 if a >= 0 {
1771 striped_random_integer_range(
1772 seed.fork("min_bit_xs"),
1773 a,
1774 Integer::power_of_2(unsigned_min_bits),
1775 mean_stripe_numerator,
1776 mean_stripe_denominator,
1777 )
1778 } else {
1779 striped_random_integer_inclusive_range(
1780 seed.fork("min_bit_xs"),
1781 a,
1782 -Integer::power_of_2(unsigned_min_bits - 1),
1783 mean_stripe_numerator,
1784 mean_stripe_denominator,
1785 )
1786 }
1787}
1788
1789fn striped_signed_max_bit_range(
1790 seed: Seed,
1791 a: Integer,
1792 unsigned_max_bits: u64,
1793 mean_stripe_numerator: u64,
1794 mean_stripe_denominator: u64,
1795) -> StripedRandomIntegerInclusiveRange {
1796 if a > 0 {
1797 striped_random_integer_inclusive_range(
1798 seed.fork("max_bit_xs"),
1799 Integer::power_of_2(unsigned_max_bits - 1),
1800 a,
1801 mean_stripe_numerator,
1802 mean_stripe_denominator,
1803 )
1804 } else {
1805 // also handles a == 0
1806 striped_random_integer_inclusive_range(
1807 seed.fork("max_bit_xs"),
1808 -Integer::power_of_2(unsigned_max_bits) + Integer::ONE,
1809 a,
1810 mean_stripe_numerator,
1811 mean_stripe_denominator,
1812 )
1813 }
1814}
1815
1816/// Generates striped random [`Integer`]s greater than or equal to a lower bound, or less than or
1817/// equal to an upper bound.
1818#[derive(Clone, Debug)]
1819pub struct StripedRandomIntegerRangeToInfinity {
1820 boundary_bits: i64,
1821 bits: GeometricRandomSignedRange<i64>,
1822 bit_source: StripedBitSource,
1823 boundary_bit_xs: StripedRandomIntegerInclusiveRange,
1824}
1825
1826impl Iterator for StripedRandomIntegerRangeToInfinity {
1827 type Item = Integer;
1828
1829 fn next(&mut self) -> Option<Integer> {
1830 let bits = self.bits.next().unwrap();
1831 if bits == self.boundary_bits {
1832 self.boundary_bit_xs.next()
1833 } else {
1834 Some(Integer::from_sign_and_abs(
1835 bits >= 0,
1836 get_striped_random_natural_with_bits(&mut self.bit_source, bits.unsigned_abs()),
1837 ))
1838 }
1839 }
1840}
1841
1842/// Generates striped random [`Integer`]s greater than or equal to a lower bound $a$.
1843///
1844/// The mean bit length $m$ of the [`Integer`]s is specified; it must be greater than the bit length
1845/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
1846///
1847/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
1848/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
1849/// is not typical).
1850///
1851/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
1852/// length will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher
1853/// mean run length.
1854///
1855/// The output length is infinite.
1856///
1857/// See [`StripedBitSource`] for information about generating striped random numbers.
1858///
1859/// # Expected complexity per iteration
1860/// $T(n, m) = O(n + m)$
1861///
1862/// $M(n, m) = O(n / m)$
1863///
1864/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1865/// `mean_precision_denominator`.
1866///
1867/// # Panics
1868/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
1869/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a >
1870/// 0$ and their ratio is less than or equal to the bit length of $a$, or if they are too large and
1871/// manipulating them leads to arithmetic overflow.
1872///
1873/// # Examples
1874/// ```
1875/// use malachite_base::iterators::prefix_to_string;
1876/// use malachite_base::random::EXAMPLE_SEED;
1877/// use malachite_nz::integer::random::striped_random_integer_range_to_infinity;
1878/// use malachite_nz::integer::Integer;
1879///
1880/// assert_eq!(
1881/// prefix_to_string(
1882/// striped_random_integer_range_to_infinity(
1883/// EXAMPLE_SEED,
1884/// Integer::from(-1000),
1885/// 20,
1886/// 1,
1887/// 10,
1888/// 1
1889/// ),
1890/// 10
1891/// ),
1892/// "[8192, 2, 1024, 33554400, -128, 1023, 8, 14745599, -256, -67, ...]"
1893/// )
1894/// ```
1895pub fn striped_random_integer_range_to_infinity(
1896 seed: Seed,
1897 a: Integer,
1898 mean_stripe_numerator: u64,
1899 mean_stripe_denominator: u64,
1900 mean_bits_numerator: u64,
1901 mean_bits_denominator: u64,
1902) -> StripedRandomIntegerRangeToInfinity {
1903 let (unsigned_min_bits, min_bits) = signed_significant_bits(&a);
1904 StripedRandomIntegerRangeToInfinity {
1905 boundary_bits: min_bits,
1906 bits: geometric_random_signed_inclusive_range(
1907 seed.fork("bits"),
1908 min_bits,
1909 i64::MAX,
1910 mean_bits_numerator,
1911 mean_bits_denominator,
1912 ),
1913 bit_source: StripedBitSource::new(
1914 seed.fork("bit_source"),
1915 mean_stripe_numerator,
1916 mean_stripe_denominator,
1917 ),
1918 boundary_bit_xs: striped_signed_min_bit_range(
1919 seed.fork("min_bit_xs"),
1920 a,
1921 unsigned_min_bits,
1922 mean_stripe_numerator,
1923 mean_stripe_denominator,
1924 ),
1925 }
1926}
1927
1928/// Generates a striped random [`Integer`] greater than or equal to a lower bound $a$.
1929///
1930/// The mean bit length $m$ of the [`Integer`] is specified; it must be greater than the bit length
1931/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
1932///
1933/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
1934/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
1935/// is not typical).
1936///
1937/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
1938/// will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher mean run
1939/// length.
1940///
1941/// See [`StripedBitSource`] for information about generating striped random numbers.
1942///
1943/// # Expected complexity
1944/// $T(n, m) = O(n + m)$
1945///
1946/// $M(n, m) = O(n / m)$
1947///
1948/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1949/// `mean_precision_denominator`.
1950///
1951/// # Panics
1952/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a > 0$ and their ratio
1953/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1954/// leads to arithmetic overflow.
1955///
1956/// # Examples
1957/// ```
1958/// use malachite_base::num::random::striped::StripedBitSource;
1959/// use malachite_base::num::random::VariableRangeGenerator;
1960/// use malachite_base::random::EXAMPLE_SEED;
1961/// use malachite_nz::integer::random::get_striped_random_integer_from_range_to_infinity;
1962/// use malachite_nz::integer::Integer;
1963///
1964/// assert_eq!(
1965/// get_striped_random_integer_from_range_to_infinity(
1966/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1),
1967/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1968/// Integer::from(-1000),
1969/// 20,
1970/// 1
1971/// ),
1972/// -3
1973/// );
1974/// ```
1975pub fn get_striped_random_integer_from_range_to_infinity(
1976 xs: &mut StripedBitSource,
1977 range_generator: &mut VariableRangeGenerator,
1978 a: Integer,
1979 mean_bits_numerator: u64,
1980 mean_bits_denominator: u64,
1981) -> Integer {
1982 let (unsigned_min_bits, min_bits) = signed_significant_bits(&a);
1983 let bits = get_geometric_random_signed_from_inclusive_range(
1984 range_generator,
1985 min_bits,
1986 i64::MAX,
1987 mean_bits_numerator,
1988 mean_bits_denominator,
1989 );
1990 if bits == min_bits {
1991 get_striped_random_integer_from_signed_min_bit_range(
1992 xs,
1993 range_generator,
1994 a,
1995 unsigned_min_bits,
1996 )
1997 } else {
1998 Integer::from_sign_and_abs(
1999 bits >= 0,
2000 get_striped_random_natural_with_bits(xs, bits.unsigned_abs()),
2001 )
2002 }
2003}
2004
2005/// Generates a striped random [`Integer`] less than or equal to an upper bound $a$.
2006///
2007/// The mean bit length $m$ of the [`Integer`] is specified; it must be greater than the bit length
2008/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
2009///
2010/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
2011/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
2012/// is not typical).
2013///
2014/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
2015/// will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher mean run
2016/// length.
2017///
2018/// See [`StripedBitSource`] for information about generating striped random numbers.
2019///
2020/// # Expected complexity
2021/// $T(n, m) = O(n + m)$
2022///
2023/// $M(n, m) = O(n / m)$
2024///
2025/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
2026/// `mean_precision_denominator`.
2027///
2028/// # Panics
2029/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $b < 0$ and their ratio
2030/// is less than or equal to the bit length of $b$, or if they are too large and manipulating them
2031/// leads to arithmetic overflow.
2032///
2033/// # Examples
2034/// ```
2035/// use malachite_base::num::random::striped::StripedBitSource;
2036/// use malachite_base::num::random::VariableRangeGenerator;
2037/// use malachite_base::random::EXAMPLE_SEED;
2038/// use malachite_nz::integer::random::get_striped_random_integer_from_range_to_negative_infinity;
2039/// use malachite_nz::integer::Integer;
2040///
2041/// assert_eq!(
2042/// get_striped_random_integer_from_range_to_negative_infinity(
2043/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1),
2044/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
2045/// Integer::from(-1000),
2046/// 20,
2047/// 1
2048/// ),
2049/// -3975
2050/// );
2051/// ```
2052pub fn get_striped_random_integer_from_range_to_negative_infinity(
2053 xs: &mut StripedBitSource,
2054 range_generator: &mut VariableRangeGenerator,
2055 a: Integer,
2056 mean_bits_numerator: u64,
2057 mean_bits_denominator: u64,
2058) -> Integer {
2059 let (unsigned_max_bits, max_bits) = signed_significant_bits(&a);
2060 let bits = get_geometric_random_signed_from_inclusive_range(
2061 range_generator,
2062 i64::MIN,
2063 max_bits,
2064 mean_bits_numerator,
2065 mean_bits_denominator,
2066 );
2067 if bits == max_bits {
2068 get_striped_random_integer_from_signed_max_bit_range(
2069 xs,
2070 range_generator,
2071 a,
2072 unsigned_max_bits,
2073 )
2074 } else {
2075 Integer::from_sign_and_abs(
2076 bits >= 0,
2077 get_striped_random_natural_with_bits(xs, bits.unsigned_abs()),
2078 )
2079 }
2080}
2081
2082/// Generates striped random [`Integer`]s less than or equal to an upper bound $a$.
2083///
2084/// The mean bit length $m$ of the [`Integer`]s is specified; it must be greater than the bit length
2085/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
2086///
2087/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
2088/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
2089/// is not typical).
2090///
2091/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
2092/// length will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher
2093/// mean run length.
2094///
2095/// The output length is infinite.
2096///
2097/// See [`StripedBitSource`] for information about generating striped random numbers.
2098///
2099/// # Expected complexity per iteration
2100/// $T(n, m) = O(n + m)$
2101///
2102/// $M(n, m) = O(n / m)$
2103///
2104/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
2105/// `mean_precision_denominator`.
2106///
2107/// # Panics
2108/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
2109/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $b <
2110/// 0$ and their ratio is less than or equal to the bit length of $b$, or if they are too large and
2111/// manipulating them leads to arithmetic overflow.
2112///
2113/// # Examples
2114/// ```
2115/// use malachite_base::iterators::prefix_to_string;
2116/// use malachite_base::random::EXAMPLE_SEED;
2117/// use malachite_nz::integer::random::striped_random_integer_range_to_negative_infinity;
2118/// use malachite_nz::integer::Integer;
2119///
2120/// assert_eq!(
2121/// prefix_to_string(
2122/// striped_random_integer_range_to_negative_infinity(
2123/// EXAMPLE_SEED,
2124/// Integer::from(1000),
2125/// 20,
2126/// 1,
2127/// 10,
2128/// 1
2129/// ),
2130/// 10
2131/// ),
2132/// "[4, 2, -1024, -144115188075919360, -516096, 992, -15, -16776704, 511, 64, ...]"
2133/// )
2134/// ```
2135pub fn striped_random_integer_range_to_negative_infinity(
2136 seed: Seed,
2137 a: Integer,
2138 mean_stripe_numerator: u64,
2139 mean_stripe_denominator: u64,
2140 mean_bits_numerator: u64,
2141 mean_bits_denominator: u64,
2142) -> StripedRandomIntegerRangeToInfinity {
2143 let (unsigned_max_bits, max_bits) = signed_significant_bits(&a);
2144 StripedRandomIntegerRangeToInfinity {
2145 boundary_bits: max_bits,
2146 bits: geometric_random_signed_inclusive_range(
2147 seed.fork("bits"),
2148 i64::MIN,
2149 max_bits,
2150 mean_bits_numerator,
2151 mean_bits_denominator,
2152 ),
2153 bit_source: StripedBitSource::new(
2154 seed.fork("bit_source"),
2155 mean_stripe_numerator,
2156 mean_stripe_denominator,
2157 ),
2158 boundary_bit_xs: striped_signed_max_bit_range(
2159 seed.fork("max_bit_xs"),
2160 a,
2161 unsigned_max_bits,
2162 mean_stripe_numerator,
2163 mean_stripe_denominator,
2164 ),
2165 }
2166}