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 RandomIntegerRange::SingleOrder(xs) => xs.next(),
1310 RandomIntegerRange::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 StripedRandomIntegerInclusiveRange::NonNegative(xs) => xs.next().map(Integer::from),
1487 StripedRandomIntegerInclusiveRange::Negative(xs) => {
1488 xs.next().map(|x| Integer::from_sign_and_abs(false, x))
1489 }
1490 StripedRandomIntegerInclusiveRange::Both(bs, xs_nn, xs_n) => {
1491 if bs.next().unwrap() {
1492 xs_nn.next().map(Integer::from)
1493 } else {
1494 xs_n.next().map(|x| Integer::from_sign_and_abs(false, x))
1495 }
1496 }
1497 }
1498 }
1499}
1500
1501/// Generates random striped [`Integer`]s in the range $[a, b)$.
1502///
1503/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
1504/// length will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean
1505/// run length.
1506///
1507/// The output length is infinite.
1508///
1509/// See [`StripedBitSource`] for information about generating striped random numbers.
1510///
1511/// # Expected complexity per iteration
1512/// $T(n) = O(n)$
1513///
1514/// $M(n) = O(n)$
1515///
1516/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1517/// b.significant_bits())`.
1518///
1519/// # Panics
1520/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <=
1521/// mean_stripe_denominator`, or if $a \geq b$.
1522///
1523/// # Examples
1524/// ```
1525/// use malachite_base::iterators::prefix_to_string;
1526/// use malachite_base::random::EXAMPLE_SEED;
1527/// use malachite_base::strings::ToBinaryString;
1528/// use malachite_nz::integer::random::striped_random_integer_range;
1529/// use malachite_nz::integer::Integer;
1530///
1531/// assert_eq!(
1532/// prefix_to_string(
1533/// striped_random_integer_range(EXAMPLE_SEED, Integer::from(-4), Integer::from(7), 4, 1)
1534/// .map(|x| x.to_binary_string()),
1535/// 10
1536/// ),
1537/// "[-100, -100, 110, 11, -100, 0, 110, 11, 0, 110, ...]"
1538/// );
1539/// ```
1540#[inline]
1541pub fn striped_random_integer_range(
1542 seed: Seed,
1543 a: Integer,
1544 b: Integer,
1545 mean_stripe_numerator: u64,
1546 mean_stripe_denominator: u64,
1547) -> StripedRandomIntegerInclusiveRange {
1548 assert!(a < b);
1549 striped_random_integer_inclusive_range(
1550 seed,
1551 a,
1552 b - Integer::ONE,
1553 mean_stripe_numerator,
1554 mean_stripe_denominator,
1555 )
1556}
1557
1558/// Generates random striped [`Integer`]s in the range $[a, b]$.
1559///
1560/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
1561/// length will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean
1562/// run length.
1563///
1564/// The output length is infinite.
1565///
1566/// See [`StripedBitSource`] for information about generating striped random numbers.
1567///
1568/// # Expected complexity per iteration
1569/// $T(n) = O(n)$
1570///
1571/// $M(n) = O(n)$
1572///
1573/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1574/// b.significant_bits())`.
1575///
1576/// # Panics
1577/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <=
1578/// mean_stripe_denominator`, or if $a > b$.
1579///
1580/// # Examples
1581/// ```
1582/// use malachite_base::iterators::prefix_to_string;
1583/// use malachite_base::random::EXAMPLE_SEED;
1584/// use malachite_base::strings::ToBinaryString;
1585/// use malachite_nz::integer::random::striped_random_integer_inclusive_range;
1586/// use malachite_nz::integer::Integer;
1587///
1588/// assert_eq!(
1589/// prefix_to_string(
1590/// striped_random_integer_inclusive_range(
1591/// EXAMPLE_SEED,
1592/// Integer::from(-4),
1593/// Integer::from(6),
1594/// 4,
1595/// 1
1596/// )
1597/// .map(|x| x.to_binary_string()),
1598/// 10
1599/// ),
1600/// "[-100, -100, 110, 11, -100, 0, 110, 11, 0, 110, ...]"
1601/// );
1602/// ```
1603pub fn striped_random_integer_inclusive_range(
1604 seed: Seed,
1605 a: Integer,
1606 b: Integer,
1607 mean_stripe_numerator: u64,
1608 mean_stripe_denominator: u64,
1609) -> StripedRandomIntegerInclusiveRange {
1610 assert!(a <= b);
1611 if a >= 0u32 {
1612 StripedRandomIntegerInclusiveRange::NonNegative(striped_random_natural_inclusive_range(
1613 seed,
1614 a.unsigned_abs(),
1615 b.unsigned_abs(),
1616 mean_stripe_numerator,
1617 mean_stripe_denominator,
1618 ))
1619 } else if b < 0u32 {
1620 StripedRandomIntegerInclusiveRange::Negative(striped_random_natural_inclusive_range(
1621 seed,
1622 b.unsigned_abs(),
1623 a.unsigned_abs(),
1624 mean_stripe_numerator,
1625 mean_stripe_denominator,
1626 ))
1627 } else {
1628 StripedRandomIntegerInclusiveRange::Both(
1629 random_bools(seed.fork("sign")),
1630 Box::new(striped_random_natural_inclusive_range(
1631 seed.fork("non-negative"),
1632 Natural::ZERO,
1633 b.unsigned_abs(),
1634 mean_stripe_numerator,
1635 mean_stripe_denominator,
1636 )),
1637 Box::new(striped_random_natural_inclusive_range(
1638 seed.fork("negative"),
1639 Natural::ONE,
1640 a.unsigned_abs(),
1641 mean_stripe_numerator,
1642 mean_stripe_denominator,
1643 )),
1644 )
1645 }
1646}
1647
1648/// Generates a random striped [`Integer`] in the range $[a, b)$.
1649///
1650/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
1651/// will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean run
1652/// length.
1653///
1654/// See [`StripedBitSource`] for information about generating striped random numbers.
1655///
1656/// # Expected complexity
1657/// $T(n) = O(n)$
1658///
1659/// $M(n) = O(n)$
1660///
1661/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1662/// b.significant_bits())`.
1663///
1664/// # Panics
1665/// Panics if $a \geq b$.
1666///
1667/// # Examples
1668/// ```
1669/// use malachite_base::num::random::striped::StripedBitSource;
1670/// use malachite_base::num::random::VariableRangeGenerator;
1671/// use malachite_base::random::EXAMPLE_SEED;
1672/// use malachite_nz::integer::random::get_striped_random_integer_from_range;
1673/// use malachite_nz::integer::Integer;
1674///
1675/// assert_eq!(
1676/// get_striped_random_integer_from_range(
1677/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1,),
1678/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1679/// Integer::from(-4),
1680/// Integer::from(7),
1681/// ),
1682/// -4
1683/// );
1684/// ```
1685#[inline]
1686pub fn get_striped_random_integer_from_range(
1687 xs: &mut StripedBitSource,
1688 range_generator: &mut VariableRangeGenerator,
1689 a: Integer,
1690 b: Integer,
1691) -> Integer {
1692 assert!(a < b);
1693 get_striped_random_integer_from_inclusive_range(xs, range_generator, a, b - Integer::ONE)
1694}
1695
1696/// Generates a random striped [`Integer`] in the range $[a, b]$.
1697///
1698/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
1699/// will usually not be $m$. Nonetheless, setting a higher $m$ will result in a higher mean run
1700/// length.
1701///
1702/// See [`StripedBitSource`] for information about generating striped random numbers.
1703///
1704/// # Expected complexity
1705/// $T(n) = O(n)$
1706///
1707/// $M(n) = O(n)$
1708///
1709/// where $T$ is time, $M$ is additional memory, and $n$ is `max(a.significant_bits(),
1710/// b.significant_bits())`.
1711///
1712/// # Panics
1713/// Panics if $a > b$.
1714///
1715/// # Examples
1716/// ```
1717/// use malachite_base::num::random::striped::StripedBitSource;
1718/// use malachite_base::num::random::VariableRangeGenerator;
1719/// use malachite_base::random::EXAMPLE_SEED;
1720/// use malachite_nz::integer::random::get_striped_random_integer_from_inclusive_range;
1721/// use malachite_nz::integer::Integer;
1722///
1723/// assert_eq!(
1724/// get_striped_random_integer_from_inclusive_range(
1725/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1,),
1726/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1727/// Integer::from(-4),
1728/// Integer::from(7),
1729/// ),
1730/// -4
1731/// );
1732/// ```
1733pub fn get_striped_random_integer_from_inclusive_range(
1734 xs: &mut StripedBitSource,
1735 range_generator: &mut VariableRangeGenerator,
1736 a: Integer,
1737 b: Integer,
1738) -> Integer {
1739 assert!(a <= b);
1740 if a >= 0u32 {
1741 Integer::from(get_striped_random_natural_from_inclusive_range(
1742 xs,
1743 a.unsigned_abs(),
1744 b.unsigned_abs(),
1745 ))
1746 } else if b < 0u32 {
1747 Integer::from_sign_and_abs(
1748 false,
1749 get_striped_random_natural_from_inclusive_range(xs, b.unsigned_abs(), a.unsigned_abs()),
1750 )
1751 } else if range_generator.next_bool() {
1752 Integer::from(get_striped_random_natural_from_inclusive_range(
1753 xs,
1754 Natural::ZERO,
1755 b.unsigned_abs(),
1756 ))
1757 } else {
1758 Integer::from_sign_and_abs(
1759 false,
1760 get_striped_random_natural_from_inclusive_range(xs, Natural::ONE, a.unsigned_abs()),
1761 )
1762 }
1763}
1764
1765fn striped_signed_min_bit_range(
1766 seed: Seed,
1767 a: Integer,
1768 unsigned_min_bits: u64,
1769 mean_stripe_numerator: u64,
1770 mean_stripe_denominator: u64,
1771) -> StripedRandomIntegerInclusiveRange {
1772 if a >= 0 {
1773 striped_random_integer_range(
1774 seed.fork("min_bit_xs"),
1775 a,
1776 Integer::power_of_2(unsigned_min_bits),
1777 mean_stripe_numerator,
1778 mean_stripe_denominator,
1779 )
1780 } else {
1781 striped_random_integer_inclusive_range(
1782 seed.fork("min_bit_xs"),
1783 a,
1784 -Integer::power_of_2(unsigned_min_bits - 1),
1785 mean_stripe_numerator,
1786 mean_stripe_denominator,
1787 )
1788 }
1789}
1790
1791fn striped_signed_max_bit_range(
1792 seed: Seed,
1793 a: Integer,
1794 unsigned_max_bits: u64,
1795 mean_stripe_numerator: u64,
1796 mean_stripe_denominator: u64,
1797) -> StripedRandomIntegerInclusiveRange {
1798 if a > 0 {
1799 striped_random_integer_inclusive_range(
1800 seed.fork("max_bit_xs"),
1801 Integer::power_of_2(unsigned_max_bits - 1),
1802 a,
1803 mean_stripe_numerator,
1804 mean_stripe_denominator,
1805 )
1806 } else {
1807 // also handles a == 0
1808 striped_random_integer_inclusive_range(
1809 seed.fork("max_bit_xs"),
1810 -Integer::power_of_2(unsigned_max_bits) + Integer::ONE,
1811 a,
1812 mean_stripe_numerator,
1813 mean_stripe_denominator,
1814 )
1815 }
1816}
1817
1818/// Generates striped random [`Integer`]s greater than or equal to a lower bound, or less than or
1819/// equal to an upper bound.
1820#[derive(Clone, Debug)]
1821pub struct StripedRandomIntegerRangeToInfinity {
1822 boundary_bits: i64,
1823 bits: GeometricRandomSignedRange<i64>,
1824 bit_source: StripedBitSource,
1825 boundary_bit_xs: StripedRandomIntegerInclusiveRange,
1826}
1827
1828impl Iterator for StripedRandomIntegerRangeToInfinity {
1829 type Item = Integer;
1830
1831 fn next(&mut self) -> Option<Integer> {
1832 let bits = self.bits.next().unwrap();
1833 if bits == self.boundary_bits {
1834 self.boundary_bit_xs.next()
1835 } else {
1836 Some(Integer::from_sign_and_abs(
1837 bits >= 0,
1838 get_striped_random_natural_with_bits(&mut self.bit_source, bits.unsigned_abs()),
1839 ))
1840 }
1841 }
1842}
1843
1844/// Generates striped random [`Integer`]s greater than or equal to a lower bound $a$.
1845///
1846/// The mean bit length $m$ of the [`Integer`]s is specified; it must be greater than the bit length
1847/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
1848///
1849/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
1850/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
1851/// is not typical).
1852///
1853/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
1854/// length will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher
1855/// mean run length.
1856///
1857/// The output length is infinite.
1858///
1859/// See [`StripedBitSource`] for information about generating striped random numbers.
1860///
1861/// # Expected complexity per iteration
1862/// $T(n, m) = O(n + m)$
1863///
1864/// $M(n, m) = O(n / m)$
1865///
1866/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1867/// `mean_precision_denominator`.
1868///
1869/// # Panics
1870/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
1871/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a >
1872/// 0$ and their ratio is less than or equal to the bit length of $a$, or if they are too large and
1873/// manipulating them leads to arithmetic overflow.
1874///
1875/// # Examples
1876/// ```
1877/// use malachite_base::iterators::prefix_to_string;
1878/// use malachite_base::random::EXAMPLE_SEED;
1879/// use malachite_nz::integer::random::striped_random_integer_range_to_infinity;
1880/// use malachite_nz::integer::Integer;
1881///
1882/// assert_eq!(
1883/// prefix_to_string(
1884/// striped_random_integer_range_to_infinity(
1885/// EXAMPLE_SEED,
1886/// Integer::from(-1000),
1887/// 20,
1888/// 1,
1889/// 10,
1890/// 1
1891/// ),
1892/// 10
1893/// ),
1894/// "[8192, 2, 1024, 33554400, -128, 1023, 8, 14745599, -256, -67, ...]"
1895/// )
1896/// ```
1897pub fn striped_random_integer_range_to_infinity(
1898 seed: Seed,
1899 a: Integer,
1900 mean_stripe_numerator: u64,
1901 mean_stripe_denominator: u64,
1902 mean_bits_numerator: u64,
1903 mean_bits_denominator: u64,
1904) -> StripedRandomIntegerRangeToInfinity {
1905 let (unsigned_min_bits, min_bits) = signed_significant_bits(&a);
1906 StripedRandomIntegerRangeToInfinity {
1907 boundary_bits: min_bits,
1908 bits: geometric_random_signed_inclusive_range(
1909 seed.fork("bits"),
1910 min_bits,
1911 i64::MAX,
1912 mean_bits_numerator,
1913 mean_bits_denominator,
1914 ),
1915 bit_source: StripedBitSource::new(
1916 seed.fork("bit_source"),
1917 mean_stripe_numerator,
1918 mean_stripe_denominator,
1919 ),
1920 boundary_bit_xs: striped_signed_min_bit_range(
1921 seed.fork("min_bit_xs"),
1922 a,
1923 unsigned_min_bits,
1924 mean_stripe_numerator,
1925 mean_stripe_denominator,
1926 ),
1927 }
1928}
1929
1930/// Generates a striped random [`Integer`] greater than or equal to a lower bound $a$.
1931///
1932/// The mean bit length $m$ of the [`Integer`] is specified; it must be greater than the bit length
1933/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
1934///
1935/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
1936/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
1937/// is not typical).
1938///
1939/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
1940/// will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher mean run
1941/// length.
1942///
1943/// See [`StripedBitSource`] for information about generating striped random numbers.
1944///
1945/// # Expected complexity
1946/// $T(n, m) = O(n + m)$
1947///
1948/// $M(n, m) = O(n / m)$
1949///
1950/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
1951/// `mean_precision_denominator`.
1952///
1953/// # Panics
1954/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a > 0$ and their ratio
1955/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1956/// leads to arithmetic overflow.
1957///
1958/// # Examples
1959/// ```
1960/// use malachite_base::num::random::striped::StripedBitSource;
1961/// use malachite_base::num::random::VariableRangeGenerator;
1962/// use malachite_base::random::EXAMPLE_SEED;
1963/// use malachite_nz::integer::random::get_striped_random_integer_from_range_to_infinity;
1964/// use malachite_nz::integer::Integer;
1965///
1966/// assert_eq!(
1967/// get_striped_random_integer_from_range_to_infinity(
1968/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1,),
1969/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
1970/// Integer::from(-1000),
1971/// 20,
1972/// 1
1973/// ),
1974/// -3
1975/// );
1976/// ```
1977pub fn get_striped_random_integer_from_range_to_infinity(
1978 xs: &mut StripedBitSource,
1979 range_generator: &mut VariableRangeGenerator,
1980 a: Integer,
1981 mean_bits_numerator: u64,
1982 mean_bits_denominator: u64,
1983) -> Integer {
1984 let (unsigned_min_bits, min_bits) = signed_significant_bits(&a);
1985 let bits = get_geometric_random_signed_from_inclusive_range(
1986 range_generator,
1987 min_bits,
1988 i64::MAX,
1989 mean_bits_numerator,
1990 mean_bits_denominator,
1991 );
1992 if bits == min_bits {
1993 get_striped_random_integer_from_signed_min_bit_range(
1994 xs,
1995 range_generator,
1996 a,
1997 unsigned_min_bits,
1998 )
1999 } else {
2000 Integer::from_sign_and_abs(
2001 bits >= 0,
2002 get_striped_random_natural_with_bits(xs, bits.unsigned_abs()),
2003 )
2004 }
2005}
2006
2007/// Generates a striped random [`Integer`] less than or equal to an upper bound $a$.
2008///
2009/// The mean bit length $m$ of the [`Integer`] is specified; it must be greater than the bit length
2010/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
2011///
2012/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
2013/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
2014/// is not typical).
2015///
2016/// Because the [`Integer`] is constrained to be within a certain range, the actual mean run length
2017/// will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher mean run
2018/// length.
2019///
2020/// See [`StripedBitSource`] for information about generating striped random numbers.
2021///
2022/// # Expected complexity
2023/// $T(n, m) = O(n + m)$
2024///
2025/// $M(n, m) = O(n / m)$
2026///
2027/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
2028/// `mean_precision_denominator`.
2029///
2030/// # Panics
2031/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $b < 0$ and their ratio
2032/// is less than or equal to the bit length of $b$, or if they are too large and manipulating them
2033/// leads to arithmetic overflow.
2034///
2035/// # Examples
2036/// ```
2037/// use malachite_base::num::random::striped::StripedBitSource;
2038/// use malachite_base::num::random::VariableRangeGenerator;
2039/// use malachite_base::random::EXAMPLE_SEED;
2040/// use malachite_nz::integer::random::get_striped_random_integer_from_range_to_negative_infinity;
2041/// use malachite_nz::integer::Integer;
2042///
2043/// assert_eq!(
2044/// get_striped_random_integer_from_range_to_negative_infinity(
2045/// &mut StripedBitSource::new(EXAMPLE_SEED.fork("bs"), 10, 1,),
2046/// &mut VariableRangeGenerator::new(EXAMPLE_SEED.fork("rg")),
2047/// Integer::from(-1000),
2048/// 20,
2049/// 1
2050/// ),
2051/// -3975
2052/// );
2053/// ```
2054pub fn get_striped_random_integer_from_range_to_negative_infinity(
2055 xs: &mut StripedBitSource,
2056 range_generator: &mut VariableRangeGenerator,
2057 a: Integer,
2058 mean_bits_numerator: u64,
2059 mean_bits_denominator: u64,
2060) -> Integer {
2061 let (unsigned_max_bits, max_bits) = signed_significant_bits(&a);
2062 let bits = get_geometric_random_signed_from_inclusive_range(
2063 range_generator,
2064 i64::MIN,
2065 max_bits,
2066 mean_bits_numerator,
2067 mean_bits_denominator,
2068 );
2069 if bits == max_bits {
2070 get_striped_random_integer_from_signed_max_bit_range(
2071 xs,
2072 range_generator,
2073 a,
2074 unsigned_max_bits,
2075 )
2076 } else {
2077 Integer::from_sign_and_abs(
2078 bits >= 0,
2079 get_striped_random_natural_with_bits(xs, bits.unsigned_abs()),
2080 )
2081 }
2082}
2083
2084/// Generates striped random [`Integer`]s less than or equal to an upper bound $a$.
2085///
2086/// The mean bit length $m$ of the [`Integer`]s is specified; it must be greater than the bit length
2087/// of $a$. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
2088///
2089/// The actual bit length is chosen from a geometric distribution with lower bound $a$ and mean $m$.
2090/// The resulting distribution has no mean or higher-order statistics (unless $a < m < a + 1$, which
2091/// is not typical).
2092///
2093/// Because the [`Integer`]s are constrained to be within a certain range, the actual mean run
2094/// length will usually not be $\mu$. Nonetheless, setting a higher $\mu$ will result in a higher
2095/// mean run length.
2096///
2097/// The output length is infinite.
2098///
2099/// See [`StripedBitSource`] for information about generating striped random numbers.
2100///
2101/// # Expected complexity per iteration
2102/// $T(n, m) = O(n + m)$
2103///
2104/// $M(n, m) = O(n / m)$
2105///
2106/// where $T$ is time, $M$ is additional memory, $n$ is `mean_precision_numerator`, and $m$ is
2107/// `mean_precision_denominator`.
2108///
2109/// # Panics
2110/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
2111/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $b <
2112/// 0$ and their ratio is less than or equal to the bit length of $b$, or if they are too large and
2113/// manipulating them leads to arithmetic overflow.
2114///
2115/// # Examples
2116/// ```
2117/// use malachite_base::iterators::prefix_to_string;
2118/// use malachite_base::random::EXAMPLE_SEED;
2119/// use malachite_nz::integer::random::striped_random_integer_range_to_negative_infinity;
2120/// use malachite_nz::integer::Integer;
2121///
2122/// assert_eq!(
2123/// prefix_to_string(
2124/// striped_random_integer_range_to_negative_infinity(
2125/// EXAMPLE_SEED,
2126/// Integer::from(1000),
2127/// 20,
2128/// 1,
2129/// 10,
2130/// 1
2131/// ),
2132/// 10
2133/// ),
2134/// "[4, 2, -1024, -144115188075919360, -516096, 992, -15, -16776704, 511, 64, ...]"
2135/// )
2136/// ```
2137pub fn striped_random_integer_range_to_negative_infinity(
2138 seed: Seed,
2139 a: Integer,
2140 mean_stripe_numerator: u64,
2141 mean_stripe_denominator: u64,
2142 mean_bits_numerator: u64,
2143 mean_bits_denominator: u64,
2144) -> StripedRandomIntegerRangeToInfinity {
2145 let (unsigned_max_bits, max_bits) = signed_significant_bits(&a);
2146 StripedRandomIntegerRangeToInfinity {
2147 boundary_bits: max_bits,
2148 bits: geometric_random_signed_inclusive_range(
2149 seed.fork("bits"),
2150 i64::MIN,
2151 max_bits,
2152 mean_bits_numerator,
2153 mean_bits_denominator,
2154 ),
2155 bit_source: StripedBitSource::new(
2156 seed.fork("bit_source"),
2157 mean_stripe_numerator,
2158 mean_stripe_denominator,
2159 ),
2160 boundary_bit_xs: striped_signed_max_bit_range(
2161 seed.fork("max_bit_xs"),
2162 a,
2163 unsigned_max_bits,
2164 mean_stripe_numerator,
2165 mean_stripe_denominator,
2166 ),
2167 }
2168}