Skip to main content

malachite_q/random/
mod.rs

1// Copyright © 2026 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::Rational;
10use crate::arithmetic::denominators_in_closed_interval::DenominatorsInClosedRationalInterval;
11use crate::arithmetic::traits::DenominatorsInClosedInterval;
12use crate::exhaustive::RationalsWithDenominator;
13use core::cmp::min;
14use malachite_base::bools::random::{RandomBools, random_bools};
15use malachite_base::iterators::iterator_cache::IteratorCache;
16use malachite_base::num::arithmetic::traits::{
17    CoprimeWith, Reciprocal, RoundToMultiple, UnsignedAbs,
18};
19use malachite_base::num::basic::traits::One;
20use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom};
21use malachite_base::num::logic::traits::SignificantBits;
22use malachite_base::num::random::geometric::{
23    GeometricRandomNaturalValues, geometric_random_unsigneds,
24};
25use malachite_base::num::random::striped::StripedBitSource;
26use malachite_base::num::random::{
27    RandomPrimitiveInts, VariableRangeGenerator, random_primitive_ints,
28};
29use malachite_base::random::Seed;
30use malachite_base::rounding_modes::RoundingMode::*;
31use malachite_nz::integer::Integer;
32use malachite_nz::integer::random::{
33    RandomIntegerRange, RandomIntegerRangeToInfinity, get_random_integer_from_range_to_infinity,
34    get_random_integer_from_range_to_negative_infinity,
35    get_striped_random_integer_from_range_to_infinity,
36    get_striped_random_integer_from_range_to_negative_infinity, random_integer_range,
37    random_integer_range_to_infinity, random_integer_range_to_negative_infinity,
38};
39use malachite_nz::natural::Natural;
40use malachite_nz::natural::random::{
41    RandomNaturals, StripedRandomNaturals, random_naturals, random_positive_naturals,
42    striped_random_naturals, striped_random_positive_naturals,
43};
44use std::collections::HashMap;
45
46/// Generates random non-negative [`Rational`]s, given an iterator of random [`Natural`] numerators
47/// and denominators.
48#[derive(Clone, Debug)]
49pub struct RandomRationalsFromSingle<I: Iterator<Item = Natural>> {
50    xs: I,
51}
52
53impl<I: Iterator<Item = Natural>> Iterator for RandomRationalsFromSingle<I> {
54    type Item = Rational;
55
56    fn next(&mut self) -> Option<Rational> {
57        Some(Rational::from_naturals(
58            self.xs.next().unwrap(),
59            self.xs.next().unwrap(),
60        ))
61    }
62}
63
64/// Generates random positive [`Rational`]s with a specified numerator and denominator mean bit
65/// length.
66///
67/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
68/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 1. Then the numerator
69/// and denominator are chosen from all positive [`Natural`]s with that bit length.
70///
71/// The output length is infinite.
72///
73/// # Expected complexity per iteration
74/// $T(n) = O(n (\log n)^2 \log\log n)$
75///
76/// $M(n) = O(n \log n)$
77///
78/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
79/// mean_bits_denominator`.
80///
81/// # Panics
82/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
83/// <= mean_bits_denominator`.
84///
85/// # Examples
86/// ```
87/// use malachite_base::iterators::prefix_to_string;
88/// use malachite_base::random::EXAMPLE_SEED;
89/// use malachite_q::random::random_positive_rationals;
90///
91/// assert_eq!(
92///     prefix_to_string(random_positive_rationals(EXAMPLE_SEED, 32, 1), 10),
93///     "[11/2, 89/27922830575, 46627409/3788983764809694, 8/11316951483471, \
94///     11/1005760138411689342464923704482, 948931/42716754, \
95///     81013760999253680590984897748479904878392/23, 1/97645164585502, 1558028859598/29, \
96///     200127331174844881647/4058622214797175252, ...]"
97/// )
98/// ```
99pub fn random_positive_rationals(
100    seed: Seed,
101    mean_bits_numerator: u64,
102    mean_bits_denominator: u64,
103) -> RandomRationalsFromSingle<RandomNaturals<GeometricRandomNaturalValues<u64>>> {
104    RandomRationalsFromSingle {
105        xs: random_positive_naturals(seed, mean_bits_numerator, mean_bits_denominator),
106    }
107}
108
109/// Generates random non-negative [`Rational`]s, given an iterator of random [`Natural`] numerators
110/// and an iterator of random [`Natural`] denominators.
111#[derive(Clone, Debug)]
112pub struct RandomRationalsFromDouble<I: Iterator<Item = Natural>, J: Iterator<Item = Natural>> {
113    xs: I,
114    ys: J,
115}
116
117impl<I: Iterator<Item = Natural>, J: Iterator<Item = Natural>> Iterator
118    for RandomRationalsFromDouble<I, J>
119{
120    type Item = Rational;
121
122    fn next(&mut self) -> Option<Rational> {
123        Some(Rational::from_naturals(
124            self.xs.next().unwrap(),
125            self.ys.next().unwrap(),
126        ))
127    }
128}
129
130/// Generates random non-negative [`Rational`]s with a specified numerator and denominator mean bit
131/// length.
132///
133/// The output length is infinite.
134///
135/// # Expected complexity per iteration
136/// $T(n) = O(n (\log n)^2 \log\log n)$
137///
138/// $M(n) = O(n \log n)$
139///
140/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
141/// mean_bits_denominator`.
142///
143/// # Panics
144/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
145/// <= mean_bits_denominator`.
146///
147/// # Examples
148/// ```
149/// use malachite_base::iterators::prefix_to_string;
150/// use malachite_base::random::EXAMPLE_SEED;
151/// use malachite_q::random::random_non_negative_rationals;
152///
153/// assert_eq!(
154///     prefix_to_string(random_non_negative_rationals(EXAMPLE_SEED, 32, 1), 10),
155///     "[7301/34, 4183103/1234731190583, 54812347098686/6195807891591254727, 812739/17841539017, \
156///     665/908, 677/1138982845180, 166/22491855393807861245619791028129, 270142/5, \
157///     52040856788711439301087669967/15975369961878544862054, 5718607/1953563256716085077, ...]"
158/// )
159/// ```
160pub fn random_non_negative_rationals(
161    seed: Seed,
162    mean_bits_numerator: u64,
163    mean_bits_denominator: u64,
164) -> RandomRationalsFromDouble<
165    RandomNaturals<GeometricRandomNaturalValues<u64>>,
166    RandomNaturals<GeometricRandomNaturalValues<u64>>,
167> {
168    RandomRationalsFromDouble {
169        xs: random_naturals(
170            seed.fork("numerator"),
171            mean_bits_numerator,
172            mean_bits_denominator,
173        ),
174        ys: random_positive_naturals(
175            seed.fork("denominator"),
176            mean_bits_numerator,
177            mean_bits_denominator,
178        ),
179    }
180}
181
182/// Generates random negative [`Rational`]s, given an iterator of positive [`Rational`]s.
183#[derive(Clone, Debug)]
184pub struct NegativeRationals<I: Iterator<Item = Rational>> {
185    xs: I,
186}
187
188impl<I: Iterator<Item = Rational>> Iterator for NegativeRationals<I> {
189    type Item = Rational;
190
191    fn next(&mut self) -> Option<Rational> {
192        self.xs.next().map(|mut q| {
193            q.sign = false;
194            q
195        })
196    }
197}
198
199/// Generates random negative [`Rational`]s with a specified numerator and denominator mean bit
200/// length.
201///
202/// The actual bit length is chosen from a geometric distribution with mean $m$, where $m$ is
203/// `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than 1. Then the numerator
204/// and denominator are chosen from all positive [`Natural`]s with that bit length. Finally, the
205/// resulting [`Rational`] is reduced and negated.
206///
207/// The output length is infinite.
208///
209/// # Expected complexity per iteration
210/// $T(n) = O(n (\log n)^2 \log\log n)$
211///
212/// $M(n) = O(n \log n)$
213///
214/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
215/// mean_bits_denominator`.
216///
217/// # Panics
218/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
219/// <= mean_bits_denominator`.
220///
221/// # Examples
222/// ```
223/// use malachite_base::iterators::prefix_to_string;
224/// use malachite_base::random::EXAMPLE_SEED;
225/// use malachite_q::random::random_negative_rationals;
226///
227/// assert_eq!(
228///     prefix_to_string(random_negative_rationals(EXAMPLE_SEED, 32, 1), 10),
229///     "[-11/2, -89/27922830575, -46627409/3788983764809694, -8/11316951483471, \
230///     -11/1005760138411689342464923704482, -948931/42716754, \
231///     -81013760999253680590984897748479904878392/23, -1/97645164585502, -1558028859598/29, \
232///     -200127331174844881647/4058622214797175252, ...]"
233/// )
234/// ```
235pub fn random_negative_rationals(
236    seed: Seed,
237    mean_bits_numerator: u64,
238    mean_bits_denominator: u64,
239) -> NegativeRationals<RandomRationalsFromSingle<RandomNaturals<GeometricRandomNaturalValues<u64>>>>
240{
241    NegativeRationals {
242        xs: random_positive_rationals(seed, mean_bits_numerator, mean_bits_denominator),
243    }
244}
245
246/// Generates random non-negative [`Rational`]s, given an iterator of random [`Natural`] numerators
247/// and an iterator of [`bool`] signs.
248#[derive(Clone, Debug)]
249pub struct RandomRationalsFromSingleAndSign<I: Iterator<Item = Natural>> {
250    bs: RandomBools,
251    xs: I,
252}
253
254impl<I: Iterator<Item = Natural>> Iterator for RandomRationalsFromSingleAndSign<I> {
255    type Item = Rational;
256
257    fn next(&mut self) -> Option<Rational> {
258        Some(Rational::from_sign_and_naturals(
259            self.bs.next().unwrap(),
260            self.xs.next().unwrap(),
261            self.xs.next().unwrap(),
262        ))
263    }
264}
265
266/// Generates random nonzero [`Rational`]s with a specified numerator and denominator mean bit
267/// length.
268///
269/// The output length is infinite.
270///
271/// # Expected complexity per iteration
272/// $T(n) = O(n (\log n)^2 \log\log n)$
273///
274/// $M(n) = O(n \log n)$
275///
276/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
277/// mean_bits_denominator`.
278///
279/// # Panics
280/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
281/// <= mean_bits_denominator`.
282///
283/// # Examples
284/// ```
285/// use malachite_base::iterators::prefix_to_string;
286/// use malachite_base::random::EXAMPLE_SEED;
287/// use malachite_q::random::random_nonzero_rationals;
288///
289/// assert_eq!(
290///     prefix_to_string(random_nonzero_rationals(EXAMPLE_SEED, 32, 1), 10),
291///     "[-80861953616/9687130509484985, -14557437513/313, 100721397389/392237929981, \
292///     713431423/1285, -3887883364/889, 14185/969, 12609/11359517108746272468338071, \
293///     3443/4354945, 1/29, 5551/892095, ...]"
294/// )
295/// ```
296pub fn random_nonzero_rationals(
297    seed: Seed,
298    mean_bits_numerator: u64,
299    mean_bits_denominator: u64,
300) -> RandomRationalsFromSingleAndSign<RandomNaturals<GeometricRandomNaturalValues<u64>>> {
301    RandomRationalsFromSingleAndSign {
302        bs: random_bools(seed.fork("sign")),
303        xs: random_positive_naturals(seed.fork("abs"), mean_bits_numerator, mean_bits_denominator),
304    }
305}
306
307/// Generates random non-negative [`Rational`]s, given an iterator of random [`Natural`] numerators,
308/// an iterator of random [`Natural`] denominators, and an iterator of [`bool`] signs.
309#[derive(Clone, Debug)]
310pub struct RandomRationalsFromDoubleAndSign<
311    I: Iterator<Item = Natural>,
312    J: Iterator<Item = Natural>,
313> {
314    pub bs: RandomBools,
315    pub xs: I,
316    pub ys: J,
317}
318
319impl<I: Iterator<Item = Natural>, J: Iterator<Item = Natural>> Iterator
320    for RandomRationalsFromDoubleAndSign<I, J>
321{
322    type Item = Rational;
323
324    fn next(&mut self) -> Option<Rational> {
325        Some(Rational::from_sign_and_naturals(
326            self.bs.next().unwrap(),
327            self.xs.next().unwrap(),
328            self.ys.next().unwrap(),
329        ))
330    }
331}
332
333/// Generates random [`Rational`]s with a specified numerator and denominator mean bit length.
334///
335/// The output length is infinite.
336///
337/// # Expected complexity per iteration
338/// $T(n) = O(n (\log n)^2 \log\log n)$
339///
340/// $M(n) = O(n \log n)$
341///
342/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
343/// mean_bits_denominator`.
344///
345/// # Panics
346/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero or if `mean_bits_numerator
347/// <= mean_bits_denominator`.
348///
349/// # Examples
350/// ```
351/// use malachite_base::iterators::prefix_to_string;
352/// use malachite_base::random::EXAMPLE_SEED;
353/// use malachite_q::random::random_rationals;
354///
355/// assert_eq!(
356///     prefix_to_string(random_rationals(EXAMPLE_SEED, 32, 1), 10),
357///     "[-7301/34, -4183103/1234731190583, 54812347098686/6195807891591254727, \
358///     812739/17841539017, -665/908, 677/1138982845180, 166/22491855393807861245619791028129, \
359///     270142/5, 52040856788711439301087669967/15975369961878544862054, \
360///     5718607/1953563256716085077, ...]"
361/// )
362/// ```
363pub fn random_rationals(
364    seed: Seed,
365    mean_bits_numerator: u64,
366    mean_bits_denominator: u64,
367) -> RandomRationalsFromDoubleAndSign<
368    RandomNaturals<GeometricRandomNaturalValues<u64>>,
369    RandomNaturals<GeometricRandomNaturalValues<u64>>,
370> {
371    RandomRationalsFromDoubleAndSign {
372        bs: random_bools(seed.fork("sign")),
373        xs: random_naturals(
374            seed.fork("numerator"),
375            mean_bits_numerator,
376            mean_bits_denominator,
377        ),
378        ys: random_positive_naturals(
379            seed.fork("denominator"),
380            mean_bits_numerator,
381            mean_bits_denominator,
382        ),
383    }
384}
385
386/// Generates striped random positive [`Rational`]s with a specified mean numerator and denominator
387/// bit length.
388///
389/// The actual numerator and denominator bit lengths are chosen from a geometric distribution with
390/// mean $m$, where $m$ is `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than
391/// `1`. A striped bit sequence with the given stripe parameter is generated and truncated at the
392/// bit lengths to produce the numerators and denominators. The highest bits are forced to be `1`.
393/// Finally, the [`Rational`] is reduced.
394///
395/// The output length is infinite.
396///
397/// See [`StripedBitSource`] for information about generating striped random numbers.
398///
399/// # Expected complexity per iteration
400/// $T(n) = O(n (\log n)^2 \log\log n)$
401///
402/// $M(n) = O(n \log n)$
403///
404/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
405/// mean_bits_denominator`.
406///
407/// # Panics
408/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
409/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
410/// `mean_bits_numerator <= mean_bits_denominator`.
411///
412/// # Examples
413/// ```
414/// use malachite_base::iterators::prefix_to_string;
415/// use malachite_base::random::EXAMPLE_SEED;
416/// use malachite_q::random::striped_random_positive_rationals;
417///
418/// assert_eq!(
419///     prefix_to_string(
420///         striped_random_positive_rationals(EXAMPLE_SEED, 16, 1, 32, 1),
421///         10
422///     ),
423///     "[4, 1/268681216, 75493376/9007199120523391, 8/8796094070783, \
424///     8/950737950171027935941967741439, 1040391/33554432, \
425///     2813000899879757964630563421437095845888, 1/79164837199872, 2199023255551/16, \
426///     220784470296873664512/4611685966886694919, ...]"
427/// )
428/// ```
429pub fn striped_random_positive_rationals(
430    seed: Seed,
431    mean_stripe_numerator: u64,
432    mean_stripe_denominator: u64,
433    mean_bits_numerator: u64,
434    mean_bits_denominator: u64,
435) -> RandomRationalsFromSingle<StripedRandomNaturals<GeometricRandomNaturalValues<u64>>> {
436    RandomRationalsFromSingle {
437        xs: striped_random_positive_naturals(
438            seed,
439            mean_stripe_numerator,
440            mean_stripe_denominator,
441            mean_bits_numerator,
442            mean_bits_denominator,
443        ),
444    }
445}
446
447/// Generates striped random non-positive [`Rational`]s with a specified mean numerator and
448/// denominator bit length.
449///
450/// The output length is infinite.
451///
452/// See [`StripedBitSource`] for information about generating striped random numbers.
453///
454/// # Expected complexity per iteration
455/// $T(n) = O(n (\log n)^2 \log\log n)$
456///
457/// $M(n) = O(n \log n)$
458///
459/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
460/// mean_bits_denominator`.
461///
462/// # Panics
463/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
464/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
465/// `mean_bits_numerator <= mean_bits_denominator`.
466///
467/// # Examples
468/// ```
469/// use malachite_base::iterators::prefix_to_string;
470/// use malachite_base::random::EXAMPLE_SEED;
471/// use malachite_q::random::striped_random_non_negative_rationals;
472///
473/// assert_eq!(
474///     prefix_to_string(
475///         striped_random_non_negative_rationals(EXAMPLE_SEED, 16, 1, 32, 1),
476///         10
477///     ),
478///     "[8192/127, 16776704/4396972769407, 8796093005951/648518346332962816, 87381/2863267840, \
479///     1024/2043, 51/58408828928, 85/13521606402434254795714066382848, 270335/7, \
480///     59421159664630116152453890047/9444741445172838006656, 6291455/1154891846623166464, ...]"
481/// )
482/// ```
483pub fn striped_random_non_negative_rationals(
484    seed: Seed,
485    mean_stripe_numerator: u64,
486    mean_stripe_denominator: u64,
487    mean_bits_numerator: u64,
488    mean_bits_denominator: u64,
489) -> RandomRationalsFromDouble<
490    StripedRandomNaturals<GeometricRandomNaturalValues<u64>>,
491    StripedRandomNaturals<GeometricRandomNaturalValues<u64>>,
492> {
493    RandomRationalsFromDouble {
494        xs: striped_random_naturals(
495            seed.fork("numerator"),
496            mean_stripe_numerator,
497            mean_stripe_denominator,
498            mean_bits_numerator,
499            mean_bits_denominator,
500        ),
501        ys: striped_random_positive_naturals(
502            seed.fork("denominator"),
503            mean_stripe_numerator,
504            mean_stripe_denominator,
505            mean_bits_numerator,
506            mean_bits_denominator,
507        ),
508    }
509}
510
511/// Generates striped random negative [`Rational`]s with a specified mean numerator and denominator
512/// bit length.
513///
514/// The output length is infinite.
515///
516/// See [`StripedBitSource`] for information about generating striped random numbers.
517///
518/// # Expected complexity per iteration
519/// $T(n) = O(n (\log n)^2 \log\log n)$
520///
521/// $M(n) = O(n \log n)$
522///
523/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
524/// mean_bits_denominator`.
525///
526/// # Panics
527/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
528/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
529/// `mean_bits_numerator <= mean_bits_denominator`.
530///
531/// # Examples
532/// ```
533/// use malachite_base::iterators::prefix_to_string;
534/// use malachite_base::random::EXAMPLE_SEED;
535/// use malachite_q::random::striped_random_negative_rationals;
536///
537/// assert_eq!(
538///     prefix_to_string(
539///         striped_random_negative_rationals(EXAMPLE_SEED, 16, 1, 32, 1),
540///         10
541///     ),
542///     "[-4, -1/268681216, -75493376/9007199120523391, -8/8796094070783, \
543///     -8/950737950171027935941967741439, -1040391/33554432, \
544///     -2813000899879757964630563421437095845888, -1/79164837199872, -2199023255551/16, \
545///     -220784470296873664512/4611685966886694919, ...]"
546/// )
547/// ```
548pub fn striped_random_negative_rationals(
549    seed: Seed,
550    mean_stripe_numerator: u64,
551    mean_stripe_denominator: u64,
552    mean_bits_numerator: u64,
553    mean_bits_denominator: u64,
554) -> NegativeRationals<
555    RandomRationalsFromSingle<StripedRandomNaturals<GeometricRandomNaturalValues<u64>>>,
556> {
557    NegativeRationals {
558        xs: striped_random_positive_rationals(
559            seed,
560            mean_stripe_numerator,
561            mean_stripe_denominator,
562            mean_bits_numerator,
563            mean_bits_denominator,
564        ),
565    }
566}
567
568/// Generates striped random nonzero [`Rational`]s with a specified mean numerator and denominator
569/// bit length.
570///
571/// The output length is infinite.
572///
573/// See [`StripedBitSource`] for information about generating striped random numbers.
574///
575/// # Expected complexity per iteration
576/// $T(n) = O(n (\log n)^2 \log\log n)$
577///
578/// $M(n) = O(n \log n)$
579///
580/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
581/// mean_bits_denominator`.
582///
583/// # Panics
584/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
585/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
586/// `mean_bits_numerator <= mean_bits_denominator`.
587///
588/// # Examples
589/// ```
590/// use malachite_base::iterators::prefix_to_string;
591/// use malachite_base::random::EXAMPLE_SEED;
592/// use malachite_q::random::striped_random_nonzero_rationals;
593///
594/// assert_eq!(
595///     prefix_to_string(
596///         striped_random_nonzero_rationals(EXAMPLE_SEED, 16, 1, 32, 1),
597///         10
598///     ),
599///     "[-68720000000/18006083452797439, -2545165805/29, 549754781664/1236950581247, \
600///     1065353727/2047, -2147745791/513, 16128/575, 8192/17000482516899619632318463, \
601///     18431/16778240, 1/31, 4096/526335, ...]"
602/// )
603/// ```
604pub fn striped_random_nonzero_rationals(
605    seed: Seed,
606    mean_stripe_numerator: u64,
607    mean_stripe_denominator: u64,
608    mean_bits_numerator: u64,
609    mean_bits_denominator: u64,
610) -> RandomRationalsFromSingleAndSign<StripedRandomNaturals<GeometricRandomNaturalValues<u64>>> {
611    RandomRationalsFromSingleAndSign {
612        bs: random_bools(seed.fork("sign")),
613        xs: striped_random_positive_naturals(
614            seed.fork("abs"),
615            mean_stripe_numerator,
616            mean_stripe_denominator,
617            mean_bits_numerator,
618            mean_bits_denominator,
619        ),
620    }
621}
622
623/// Generates striped random [`Rational`]s with a specified mean numerator and denominator bit
624/// length.
625///
626/// The output length is infinite.
627///
628/// See [`StripedBitSource`] for information about generating striped random numbers.
629///
630/// # Expected complexity per iteration
631/// $T(n) = O(n (\log n)^2 \log\log n)$
632///
633/// $M(n) = O(n \log n)$
634///
635/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
636/// mean_bits_denominator`.
637///
638/// # Panics
639/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
640/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, or if
641/// `mean_bits_numerator <= mean_bits_denominator`.
642///
643/// # Examples
644/// ```
645/// use malachite_base::iterators::prefix_to_string;
646/// use malachite_base::random::EXAMPLE_SEED;
647/// use malachite_q::random::striped_random_rationals;
648///
649/// assert_eq!(
650///     prefix_to_string(striped_random_rationals(EXAMPLE_SEED, 16, 1, 32, 1), 10),
651///     "[-8192/127, -16776704/4396972769407, 8796093005951/648518346332962816, 87381/2863267840, \
652///     -1024/2043, 51/58408828928, 85/13521606402434254795714066382848, 270335/7, \
653///     59421159664630116152453890047/9444741445172838006656, 6291455/1154891846623166464, ...]"
654/// )
655/// ```
656pub fn striped_random_rationals(
657    seed: Seed,
658    mean_stripe_numerator: u64,
659    mean_stripe_denominator: u64,
660    mean_bits_numerator: u64,
661    mean_bits_denominator: u64,
662) -> RandomRationalsFromDoubleAndSign<
663    StripedRandomNaturals<GeometricRandomNaturalValues<u64>>,
664    StripedRandomNaturals<GeometricRandomNaturalValues<u64>>,
665> {
666    RandomRationalsFromDoubleAndSign {
667        bs: random_bools(seed.fork("sign")),
668        xs: striped_random_naturals(
669            seed.fork("numerator"),
670            mean_stripe_numerator,
671            mean_stripe_denominator,
672            mean_bits_numerator,
673            mean_bits_denominator,
674        ),
675        ys: striped_random_positive_naturals(
676            seed.fork("denominator"),
677            mean_stripe_numerator,
678            mean_stripe_denominator,
679            mean_bits_numerator,
680            mean_bits_denominator,
681        ),
682    }
683}
684
685/// Generates random [`Rational`]s greater than or equal to a lower bound $a$ and with a specific
686/// denominator.
687///
688/// The mean bit length $m$ of the absolute values of the numerators of the generated values is
689/// specified. $m$ is equal to `mean_numerator_bits_numerator / mean_numerator_bits_denominator`.
690///
691/// The output length is infinite.
692///
693/// # Expected complexity per iteration
694/// $T(n) = O(n (\log n)^2 \log\log n)$
695///
696/// $M(n) = O(n \log n)$
697///
698/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
699/// mean_numerator_bits_denominator`.
700///
701/// # Panics
702/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a > 0$ and their ratio
703/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
704/// leads to arithmetic overflow.
705///
706/// # Examples
707/// ```
708/// use malachite_base::iterators::prefix_to_string;
709/// use malachite_base::random::EXAMPLE_SEED;
710/// use malachite_nz::natural::Natural;
711/// use malachite_q::random::random_rational_with_denominator_range_to_infinity;
712/// use malachite_q::Rational;
713///
714/// assert_eq!(
715///     prefix_to_string(
716///         random_rational_with_denominator_range_to_infinity(
717///             EXAMPLE_SEED,
718///             Natural::from(3u32),
719///             Rational::from_signeds(-3i32, 2),
720///             3,
721///             1
722///         ),
723///         10
724///     ),
725///     "[1/3, 4/3, -2/3, 94/3, 4/3, -2/3, 1/3, 145/3, 7/3, 1/3, ...]"
726/// )
727/// ```
728pub fn random_rational_with_denominator_range_to_infinity(
729    seed: Seed,
730    d: Natural,
731    a: Rational,
732    mean_numerator_bits_numerator: u64,
733    mean_numerator_bits_denominator: u64,
734) -> RationalsWithDenominator<RandomIntegerRangeToInfinity> {
735    assert_ne!(d, 0u32);
736    RationalsWithDenominator {
737        numerators: random_integer_range_to_infinity(
738            seed,
739            Integer::rounding_from(a * Rational::from(&d), Ceiling).0,
740            mean_numerator_bits_numerator,
741            mean_numerator_bits_denominator,
742        ),
743        denominator: d,
744    }
745}
746
747/// Generates random [`Rational`]s less than or equal to a lower bound $a$ and with a specific
748/// denominator.
749///
750/// The mean bit length $m$ of the absolute values of the numerators of the generated values is
751/// specified. $m$ is equal to `mean_numerator_bits_numerator / mean_numerator_bits_denominator`.
752///
753/// The output length is infinite.
754///
755/// # Expected complexity per iteration
756/// $T(n) = O(n (\log n)^2 \log\log n)$
757///
758/// $M(n) = O(n \log n)$
759///
760/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
761/// mean_numerator_bits_denominator`.
762///
763/// # Panics
764/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a < 0$ and their ratio
765/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
766/// leads to arithmetic overflow.
767///
768/// # Examples
769/// ```
770/// use malachite_base::iterators::prefix_to_string;
771/// use malachite_base::random::EXAMPLE_SEED;
772/// use malachite_nz::natural::Natural;
773/// use malachite_q::random::random_rational_with_denominator_range_to_negative_infinity;
774/// use malachite_q::Rational;
775///
776/// assert_eq!(
777///     prefix_to_string(
778///         random_rational_with_denominator_range_to_negative_infinity(
779///             EXAMPLE_SEED,
780///             Natural::from(3u32),
781///             Rational::from_unsigneds(3u32, 2),
782///             3,
783///             1
784///         ),
785///         10
786///     ),
787///     "[1/3, 4/3, -56/3, -2/3, 2/3, -1/3, -7/3, -11/3, -17/3, 4/3, ...]"
788/// )
789/// ```
790pub fn random_rational_with_denominator_range_to_negative_infinity(
791    seed: Seed,
792    d: Natural,
793    a: Rational,
794    mean_numerator_bits_numerator: u64,
795    mean_numerator_bits_denominator: u64,
796) -> RationalsWithDenominator<RandomIntegerRangeToInfinity> {
797    assert_ne!(d, 0u32);
798    RationalsWithDenominator {
799        numerators: random_integer_range_to_negative_infinity(
800            seed,
801            Integer::rounding_from(a * Rational::from(&d), Floor).0,
802            mean_numerator_bits_numerator,
803            mean_numerator_bits_denominator,
804        ),
805        denominator: d,
806    }
807}
808
809/// Generates random [`Rational`]s in the half-open interval $[a, b)$ and with a specific
810/// denominator.
811///
812/// In general, the [`Rational`]s are not generated uniformly. Instead, [`Rational`]s whose
813/// numerators have smaller bit lengths are generated more frequently.
814///
815/// The distribution of generated values is parametrized by a number $m$, given by
816/// `mean_numerator_bits_numerator / mean_numerator_bits_denominator`. It is not actually the mean
817/// bit length of the numerators, though it approaches the mean bit length of the numerators minus
818/// $\lceil ad \right$ as $\log (b/a)$ approaches infinity. $m$ cannot be 0, and must be greater
819/// than the bit length of the numerator of the generated [`Rational`] with the smallest absolute
820/// value, but it may be arbitrarily large. The smaller it is, the more quickly the probabilities
821/// decrease as bit length increases. The larger it is, the more closely the distribution approaches
822/// a uniform distribution over the bit lengths.
823///
824/// The output length is infinite.
825///
826/// # Expected complexity per iteration
827/// $T(n) = O(n (\log n)^2 \log\log n)$
828///
829/// $M(n) = O(n \log n)$
830///
831/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
832/// mean_numerator_bits_denominator`.
833///
834/// # Panics
835/// Panics if $a \geq b$, if `mean_numerator_bits_numerator` or `mean_numerator_bits_denominator`
836/// are zero, if their ratio is less than or equal to the bit length of the [`Rational`] with
837/// smallest absolute numerator in the range, or if they are too large and manipulating them leads
838/// to arithmetic overflow.
839///
840/// # Examples
841/// ```
842/// use malachite_base::iterators::prefix_to_string;
843/// use malachite_base::random::EXAMPLE_SEED;
844/// use malachite_nz::natural::Natural;
845/// use malachite_q::random::random_rational_with_denominator_range;
846/// use malachite_q::Rational;
847///
848/// assert_eq!(
849///     prefix_to_string(
850///         random_rational_with_denominator_range(
851///             EXAMPLE_SEED,
852///             Natural::from(100u32),
853///             Rational::from_unsigneds(1u32, 3),
854///             Rational::from_unsigneds(1u32, 2),
855///             3,
856///             1
857///         ),
858///         10
859///     ),
860///     "[41/100, 43/100, 41/100, 41/100, 39/100, 41/100, 49/100, 41/100, 41/100, 39/100, ...]"
861/// )
862/// ```
863pub fn random_rational_with_denominator_range(
864    seed: Seed,
865    d: Natural,
866    a: Rational,
867    b: Rational,
868    mut mean_numerator_bits_numerator: u64,
869    mut mean_numerator_bits_denominator: u64,
870) -> RationalsWithDenominator<RandomIntegerRange> {
871    assert_ne!(d, 0u32);
872    assert!(a < b);
873    let q_d = Rational::from(&d);
874    let a_i = Integer::rounding_from(a * &q_d, Ceiling).0;
875    let upper_included = b.denominator_ref() == &d;
876    let mut b_i = Integer::rounding_from(b * q_d, Floor).0;
877    if !upper_included {
878        b_i += Integer::ONE;
879    }
880    if (a_i >= 0) == (b_i >= 0) {
881        let (n, d) = (Rational::from_unsigneds(
882            mean_numerator_bits_numerator,
883            mean_numerator_bits_denominator,
884        ) + Rational::from(min(a_i.significant_bits(), b_i.significant_bits())))
885        .into_numerator_and_denominator();
886        mean_numerator_bits_numerator = u64::exact_from(&n);
887        mean_numerator_bits_denominator = u64::exact_from(&d);
888    }
889    RationalsWithDenominator {
890        numerators: random_integer_range(
891            seed,
892            a_i,
893            b_i,
894            mean_numerator_bits_numerator,
895            mean_numerator_bits_denominator,
896        ),
897        denominator: d,
898    }
899}
900
901/// Generates random [`Rational`]s in the closed interval $[a, b]$ and with a specific denominator.
902///
903/// In general, the [`Rational`]s are not generated uniformly. Instead, [`Rational`]s whose
904/// numerators have smaller bit lengths are generated more frequently.
905///
906/// The distribution of generated values is parametrized by a number $m$, given by
907/// `mean_numerator_bits_numerator / mean_numerator_bits_denominator`. It is not actually the mean
908/// bit length of the numerators, though it approaches the mean bit length of the numerators minus
909/// $\lceil ad \right$ as $\log (b/a)$ approaches infinity. $m$ cannot be 0, and must be greater
910/// than the bit length of the numerator of the generated [`Rational`] with the smallest absolute
911/// value, but it may be arbitrarily large. The smaller it is, the more quickly the probabilities
912/// decrease as bit length increases. The larger it is, the more closely the distribution approaches
913/// a uniform distribution over the bit lengths.
914///
915/// The output length is infinite.
916///
917/// # Expected complexity per iteration
918/// $T(n) = O(n (\log n)^2 \log\log n)$
919///
920/// $M(n) = O(n \log n)$
921///
922/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
923/// mean_numerator_bits_denominator`.
924///
925/// # Panics
926/// Panics if $a > b$, if `mean_numerator_bits_numerator` or `mean_numerator_bits_denominator` are
927/// zero, if their ratio is less than or equal to the bit length of the [`Rational`] with smallest
928/// absolute numerator in the range, or if they are too large and manipulating them leads to
929/// arithmetic overflow.
930///
931/// # Examples
932/// ```
933/// use malachite_base::iterators::prefix_to_string;
934/// use malachite_base::random::EXAMPLE_SEED;
935/// use malachite_nz::natural::Natural;
936/// use malachite_q::random::random_rational_with_denominator_inclusive_range;
937/// use malachite_q::Rational;
938///
939/// assert_eq!(
940///     prefix_to_string(
941///         random_rational_with_denominator_inclusive_range(
942///             EXAMPLE_SEED,
943///             Natural::from(100u32),
944///             Rational::from_unsigneds(1u32, 3),
945///             Rational::from_unsigneds(1u32, 2),
946///             3,
947///             1
948///         ),
949///         10
950///     ),
951///     "[41/100, 43/100, 41/100, 41/100, 39/100, 41/100, 49/100, 41/100, 41/100, 39/100, ...]"
952/// )
953/// ```
954pub fn random_rational_with_denominator_inclusive_range(
955    seed: Seed,
956    d: Natural,
957    a: Rational,
958    b: Rational,
959    mut mean_numerator_bits_numerator: u64,
960    mut mean_numerator_bits_denominator: u64,
961) -> RationalsWithDenominator<RandomIntegerRange> {
962    assert_ne!(d, 0u32);
963    assert!(a <= b);
964    let q_d = Rational::from(&d);
965    let a_i = Integer::rounding_from(a * &q_d, Ceiling).0;
966    let b_i = Integer::rounding_from(b * q_d, Floor).0 + Integer::ONE;
967    if (a_i >= 0) == (b_i >= 0) {
968        let (n, d) = (Rational::from_unsigneds(
969            mean_numerator_bits_numerator,
970            mean_numerator_bits_denominator,
971        ) + Rational::from(min(a_i.significant_bits(), b_i.significant_bits())))
972        .into_numerator_and_denominator();
973        mean_numerator_bits_numerator = u64::exact_from(&n);
974        mean_numerator_bits_denominator = u64::exact_from(&d);
975    }
976    RationalsWithDenominator {
977        numerators: random_integer_range(
978            seed,
979            a_i,
980            b_i,
981            mean_numerator_bits_numerator,
982            mean_numerator_bits_denominator,
983        ),
984        denominator: d,
985    }
986}
987
988/// Generates random [`Rational`]s greater than or equal to a lower bound. See
989/// [`random_rational_range_to_infinity`] for more details.
990#[derive(Clone, Debug)]
991pub struct RandomRationalRangeToInfinity {
992    a: Rational,
993    limbs: RandomPrimitiveInts<u64>,
994    range_generator: VariableRangeGenerator,
995    mean_bits_numerator: u64,
996    mean_bits_denominator: u64,
997    denominators: RandomNaturals<GeometricRandomNaturalValues<u64>>,
998}
999
1000impl Iterator for RandomRationalRangeToInfinity {
1001    type Item = Rational;
1002
1003    fn next(&mut self) -> Option<Rational> {
1004        let d = self.denominators.next().unwrap();
1005        let numerator_bound = Integer::rounding_from(&self.a * Rational::from(&d), Ceiling).0;
1006        let (numerator, denominator) = (Rational::from(d.significant_bits())
1007            + Rational::from_unsigneds(self.mean_bits_numerator, self.mean_bits_denominator))
1008        .into_numerator_and_denominator();
1009        let numerator = u64::exact_from(&numerator);
1010        let denominator = u64::exact_from(&denominator);
1011        loop {
1012            let n = get_random_integer_from_range_to_infinity(
1013                &mut self.limbs,
1014                &mut self.range_generator,
1015                numerator_bound.clone(),
1016                numerator,
1017                denominator,
1018            );
1019            if n.unsigned_abs_ref().coprime_with(&d) {
1020                return Some(Rational {
1021                    sign: n >= 0,
1022                    numerator: n.unsigned_abs(),
1023                    denominator: d,
1024                });
1025            }
1026        }
1027    }
1028}
1029
1030/// Generates random [`Rational`]s greater than or equal to a lower bound $a$.
1031///
1032/// The mean bit length $m$ of the absolute values of the numerators of the generated values is
1033/// specified. $m$ is equal to `mean_numerator_bits_numerator / mean_numerator_bits_denominator`.
1034///
1035/// The output length is infinite.
1036///
1037/// # Expected complexity per iteration
1038/// $T(n) = O(n (\log n)^2 \log\log n)$
1039///
1040/// $M(n) = O(n \log n)$
1041///
1042/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
1043/// mean_numerator_bits_denominator`.
1044///
1045/// # Panics
1046/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a > 0$ and their ratio
1047/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1048/// leads to arithmetic overflow.
1049///
1050/// # Examples
1051/// ```
1052/// use malachite_base::iterators::prefix_to_string;
1053/// use malachite_base::random::EXAMPLE_SEED;
1054/// use malachite_q::random::random_rational_range_to_infinity;
1055/// use malachite_q::Rational;
1056///
1057/// assert_eq!(
1058///     prefix_to_string(
1059///         random_rational_range_to_infinity(EXAMPLE_SEED, Rational::from_signeds(-3i32, 2), 3, 1),
1060///         10
1061///     ),
1062///     "[2/3, 56, 1/2, -1/34, -15/23, -4/5, 1/2, 5, 195, -1, ...]"
1063/// )
1064/// ```
1065pub fn random_rational_range_to_infinity(
1066    seed: Seed,
1067    a: Rational,
1068    mean_bits_numerator: u64,
1069    mean_bits_denominator: u64,
1070) -> RandomRationalRangeToInfinity {
1071    RandomRationalRangeToInfinity {
1072        a,
1073        limbs: random_primitive_ints(seed.fork("limbs")),
1074        range_generator: VariableRangeGenerator::new(seed.fork("range generator")),
1075        mean_bits_numerator,
1076        mean_bits_denominator,
1077        denominators: random_positive_naturals(
1078            seed.fork("denominators"),
1079            mean_bits_numerator,
1080            mean_bits_denominator,
1081        ),
1082    }
1083}
1084
1085/// Generates random [`Rational`]s less than or equal to a lower bound. See
1086/// [`random_rational_range_to_negative_infinity`] for more details.
1087#[derive(Clone, Debug)]
1088pub struct RandomRationalRangeToNegativeInfinity {
1089    a: Rational,
1090    limbs: RandomPrimitiveInts<u64>,
1091    range_generator: VariableRangeGenerator,
1092    mean_bits_numerator: u64,
1093    mean_bits_denominator: u64,
1094    denominators: RandomNaturals<GeometricRandomNaturalValues<u64>>,
1095}
1096
1097impl Iterator for RandomRationalRangeToNegativeInfinity {
1098    type Item = Rational;
1099
1100    fn next(&mut self) -> Option<Rational> {
1101        let d = self.denominators.next().unwrap();
1102        let numerator_bound = Integer::rounding_from(&self.a * Rational::from(&d), Floor).0;
1103        let (numerator, denominator) = (Rational::from(d.significant_bits())
1104            + Rational::from_unsigneds(self.mean_bits_numerator, self.mean_bits_denominator))
1105        .into_numerator_and_denominator();
1106        let numerator = u64::exact_from(&numerator);
1107        let denominator = u64::exact_from(&denominator);
1108        loop {
1109            let n = get_random_integer_from_range_to_negative_infinity(
1110                &mut self.limbs,
1111                &mut self.range_generator,
1112                numerator_bound.clone(),
1113                numerator,
1114                denominator,
1115            );
1116            if n.unsigned_abs_ref().coprime_with(&d) {
1117                return Some(Rational {
1118                    sign: n >= 0,
1119                    numerator: n.unsigned_abs(),
1120                    denominator: d,
1121                });
1122            }
1123        }
1124    }
1125}
1126
1127/// Generates random [`Rational`]s less than or equal to a lower bound $a$.
1128///
1129/// The mean bit length $m$ of the absolute values of the numerators of the generated values is
1130/// specified. $m$ is equal to `mean_bits_numerator / mean_bits_denominator`.
1131///
1132/// The output length is infinite.
1133///
1134/// # Expected complexity per iteration
1135/// $T(n) = O(n (\log n)^2 \log\log n)$
1136///
1137/// $M(n) = O(n \log n)$
1138///
1139/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_bits_numerator /
1140/// mean_bits_denominator`.
1141///
1142/// # Panics
1143/// Panics if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a > 0$ and their ratio
1144/// is less than or equal to the bit length of $a$, or if they are too large and manipulating them
1145/// leads to arithmetic overflow.
1146///
1147/// # Examples
1148/// ```
1149/// use malachite_base::iterators::prefix_to_string;
1150/// use malachite_base::random::EXAMPLE_SEED;
1151/// use malachite_q::random::random_rational_range_to_negative_infinity;
1152/// use malachite_q::Rational;
1153///
1154/// assert_eq!(
1155///     prefix_to_string(
1156///         random_rational_range_to_negative_infinity(
1157///             EXAMPLE_SEED,
1158///             Rational::from_signeds(-3i32, 2),
1159///             3,
1160///             1
1161///         ),
1162///         10
1163///     ),
1164///     "[-8/3, -114, -31/2, -1187/34, -61/23, -81/5, -3/2, -19, -82, -312, ...]"
1165/// )
1166/// ```
1167pub fn random_rational_range_to_negative_infinity(
1168    seed: Seed,
1169    a: Rational,
1170    mean_bits_numerator: u64,
1171    mean_bits_denominator: u64,
1172) -> RandomRationalRangeToNegativeInfinity {
1173    RandomRationalRangeToNegativeInfinity {
1174        a,
1175        limbs: random_primitive_ints(seed.fork("limbs")),
1176        range_generator: VariableRangeGenerator::new(seed.fork("range generator")),
1177        mean_bits_numerator,
1178        mean_bits_denominator,
1179        denominators: random_positive_naturals(
1180            seed.fork("denominators"),
1181            mean_bits_numerator,
1182            mean_bits_denominator,
1183        ),
1184    }
1185}
1186
1187/// Generates random [`Rational`]s in a half-open interval $[a,b)$. See [`random_rational_range`]
1188/// for more details.
1189#[derive(Clone, Debug)]
1190pub struct RandomRationalRange {
1191    seed: Seed,
1192    mean_numerator_bits_numerator: u64,
1193    mean_numerator_bits_denominator: u64,
1194    a: Rational,
1195    b: Rational,
1196    denominators: IteratorCache<DenominatorsInClosedRationalInterval>,
1197    denominator_map: HashMap<Natural, RationalsWithDenominator<RandomIntegerRange>>,
1198    indices: GeometricRandomNaturalValues<usize>,
1199}
1200
1201impl Iterator for RandomRationalRange {
1202    type Item = Rational;
1203
1204    fn next(&mut self) -> Option<Rational> {
1205        loop {
1206            let d = self.denominators.get(self.indices.next().unwrap()).unwrap();
1207            if (&self.a)
1208                .round_to_multiple(Rational::from(d).reciprocal(), Ceiling)
1209                .0
1210                >= self.b
1211            {
1212                // This can happen when d is the denominator of b
1213                continue;
1214            }
1215            return self
1216                .denominator_map
1217                .entry(d.clone())
1218                .or_insert_with(|| {
1219                    random_rational_with_denominator_range(
1220                        self.seed.fork(&d.to_string()),
1221                        d.clone(),
1222                        self.a.clone(),
1223                        self.b.clone(),
1224                        self.mean_numerator_bits_numerator,
1225                        self.mean_numerator_bits_denominator,
1226                    )
1227                })
1228                .next();
1229        }
1230    }
1231}
1232
1233/// Generates random [`Rational`]s in the half-open interval $[a, b)$.
1234///
1235/// In general, the [`Rational`]s are not generated uniformly. Instead, [`Rational`]s whose
1236/// numerators have smaller bit lengths are generated more frequently.
1237///
1238/// The distribution of generated values is parametrized by a number $m$, given by
1239/// `mean_numerator_bits_numerator / mean_numerator_bits_denominator`. It is not actually the mean
1240/// bit length of the numerators, though it approaches the mean bit length of the numerators minus
1241/// $\lceil ad \right$ as $\log (b/a)$ approaches infinity. $m$ cannot be 0, and must be greater
1242/// than the bit length of the numerator of the generated [`Rational`] with the smallest absolute
1243/// value, but it may be arbitrarily large. The smaller it is, the more quickly the probabilities
1244/// decrease as bit length increases. The larger it is, the more closely the distribution approaches
1245/// a uniform distribution over the bit lengths.
1246///
1247/// The distribution of denominators is parametrized by `mean_denominator_index_numerator /
1248/// mean_denominator_index_denominator.` The larger this value is, the larger the average
1249/// denominator produced.
1250///
1251/// The output length is infinite.
1252///
1253/// # Expected complexity per iteration
1254/// $T(n) = O(n (\log n)^2 \log\log n)$
1255///
1256/// $M(n) = O(n \log n)$
1257///
1258/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
1259/// mean_numerator_bits_denominator`.
1260///
1261/// # Panics
1262/// Panics if $a \geq b$, if `mean_numerator_bits_numerator`, `mean_numerator_bits_denominator`,
1263/// `mean_denominator_index_numerator`, or `mean_denominator_index_denominator` are zero, if
1264/// `mean_numerator_bits_numerator / mean_numerator_bits_denominator` is less than or equal to the
1265/// bit length of the [`Rational`] with smallest absolute numerator in the range, or if any of these
1266/// values are too are too large and manipulating them leads to arithmetic overflow.
1267///
1268/// # Examples
1269/// ```
1270/// use malachite_base::iterators::prefix_to_string;
1271/// use malachite_base::random::EXAMPLE_SEED;
1272/// use malachite_q::random::random_rational_range;
1273/// use malachite_q::Rational;
1274///
1275/// assert_eq!(
1276///     prefix_to_string(
1277///         random_rational_range(
1278///             EXAMPLE_SEED,
1279///             Rational::from_unsigneds(1u32, 3),
1280///             Rational::from_unsigneds(1u32, 2),
1281///             3,
1282///             1,
1283///             10,
1284///             1
1285///         ),
1286///         10
1287///     ),
1288///     "[1/3, 4/9, 7/19, 5/13, 13/28, 4/9, 5/14, 7/19, 14/33, 8/17, ...]"
1289/// )
1290/// ```
1291pub fn random_rational_range(
1292    seed: Seed,
1293    a: Rational,
1294    b: Rational,
1295    mean_numerator_bits_numerator: u64,
1296    mean_numerator_bits_denominator: u64,
1297    mean_denominator_index_numerator: u64,
1298    mean_denominator_index_denominator: u64,
1299) -> RandomRationalRange {
1300    assert!(a < b);
1301    assert_ne!(mean_numerator_bits_denominator, 0);
1302    assert_ne!(mean_denominator_index_denominator, 0);
1303    RandomRationalRange {
1304        seed: seed.fork("numerators"),
1305        mean_numerator_bits_numerator,
1306        mean_numerator_bits_denominator,
1307        a: a.clone(),
1308        b: b.clone(),
1309        denominators: IteratorCache::new(Rational::denominators_in_closed_interval(a, b)),
1310        denominator_map: HashMap::new(),
1311        indices: geometric_random_unsigneds(
1312            seed.fork("indices"),
1313            mean_denominator_index_numerator,
1314            mean_denominator_index_denominator,
1315        ),
1316    }
1317}
1318
1319#[doc(hidden)]
1320#[derive(Clone, Debug)]
1321pub struct RandomRationalInclusiveRangeInner {
1322    seed: Seed,
1323    mean_numerator_bits_numerator: u64,
1324    mean_numerator_bits_denominator: u64,
1325    a: Rational,
1326    b: Rational,
1327    denominators: IteratorCache<DenominatorsInClosedRationalInterval>,
1328    denominator_map: HashMap<Natural, RationalsWithDenominator<RandomIntegerRange>>,
1329    indices: GeometricRandomNaturalValues<usize>,
1330}
1331
1332impl Iterator for RandomRationalInclusiveRangeInner {
1333    type Item = Rational;
1334
1335    fn next(&mut self) -> Option<Rational> {
1336        let d = self.denominators.get(self.indices.next().unwrap()).unwrap();
1337        self.denominator_map
1338            .entry(d.clone())
1339            .or_insert_with(|| {
1340                random_rational_with_denominator_inclusive_range(
1341                    self.seed.fork(&d.to_string()),
1342                    d.clone(),
1343                    self.a.clone(),
1344                    self.b.clone(),
1345                    self.mean_numerator_bits_numerator,
1346                    self.mean_numerator_bits_denominator,
1347                )
1348            })
1349            .next()
1350    }
1351}
1352
1353/// Generates random [`Rational`]s in a closed interval $\[a,b\]$. See
1354/// [`random_rational_inclusive_range`] for more details.
1355#[allow(clippy::large_enum_variant)]
1356#[derive(Clone, Debug)]
1357pub enum RandomRationalInclusiveRange {
1358    Single(Rational),
1359    Multiple(RandomRationalInclusiveRangeInner),
1360}
1361
1362impl Iterator for RandomRationalInclusiveRange {
1363    type Item = Rational;
1364
1365    fn next(&mut self) -> Option<Rational> {
1366        match self {
1367            Self::Single(x) => Some(x.clone()),
1368            Self::Multiple(xs) => xs.next(),
1369        }
1370    }
1371}
1372
1373/// Generates random [`Rational`]s in the closed interval $[a, b]$.
1374///
1375/// In general, the [`Rational`]s are not generated uniformly. Instead, [`Rational`]s whose
1376/// numerators have smaller bit lengths are generated more frequently.
1377///
1378/// The distribution of generated values is parametrized by a number $m$, given by
1379/// `mean_numerator_bits_numerator / mean_numerator_bits_denominator`. It is not actually the mean
1380/// bit length of the numerators, though it approaches the mean bit length of the numerators minus
1381/// $\lceil ad \right$ as $\log (b/a)$ approaches infinity. $m$ cannot be 0, and must be greater
1382/// than the bit length of the numerator of the generated [`Rational`] with the smallest absolute
1383/// value, but it may be arbitrarily large. The smaller it is, the more quickly the probabilities
1384/// decrease as bit length increases. The larger it is, the more closely the distribution approaches
1385/// a uniform distribution over the bit lengths.
1386///
1387/// The distribution of denominators is parametrized by `mean_denominator_index_numerator /
1388/// mean_denominator_index_denominator.` The larger this value is, the larger the average
1389/// denominator produced.
1390///
1391/// The output length is infinite.
1392///
1393/// # Expected complexity per iteration
1394/// $T(n) = O(n (\log n)^2 \log\log n)$
1395///
1396/// $M(n) = O(n \log n)$
1397///
1398/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
1399/// mean_numerator_bits_denominator`.
1400///
1401/// # Panics
1402/// Panics if $a>b$, if `mean_numerator_bits_numerator`, `mean_numerator_bits_denominator`,
1403/// `mean_denominator_index_numerator`, or `mean_denominator_index_denominator` are zero, if
1404/// `mean_numerator_bits_numerator / mean_numerator_bits_denominator` is less than or equal to the
1405/// bit length of the [`Rational`] with smallest absolute numerator in the range, or if any of these
1406/// values are too are too large and manipulating them leads to arithmetic overflow.
1407///
1408/// # Examples
1409/// ```
1410/// use malachite_base::iterators::prefix_to_string;
1411/// use malachite_base::random::EXAMPLE_SEED;
1412/// use malachite_q::random::random_rational_inclusive_range;
1413/// use malachite_q::Rational;
1414///
1415/// assert_eq!(
1416///     prefix_to_string(
1417///         random_rational_inclusive_range(
1418///             EXAMPLE_SEED,
1419///             Rational::from_unsigneds(1u32, 3),
1420///             Rational::from_unsigneds(1u32, 2),
1421///             3,
1422///             1,
1423///             10,
1424///             1
1425///         ),
1426///         10
1427///     ),
1428///     "[1/3, 4/9, 1/2, 7/19, 5/13, 13/28, 1/2, 4/9, 1/2, 5/14, ...]"
1429/// )
1430/// ```
1431pub fn random_rational_inclusive_range(
1432    seed: Seed,
1433    a: Rational,
1434    b: Rational,
1435    mean_numerator_bits_numerator: u64,
1436    mean_numerator_bits_denominator: u64,
1437    mean_denominator_index_numerator: u64,
1438    mean_denominator_index_denominator: u64,
1439) -> RandomRationalInclusiveRange {
1440    assert!(a <= b);
1441    if a == b {
1442        return RandomRationalInclusiveRange::Single(a);
1443    }
1444    assert_ne!(mean_numerator_bits_denominator, 0);
1445    assert_ne!(mean_denominator_index_denominator, 0);
1446    RandomRationalInclusiveRange::Multiple(RandomRationalInclusiveRangeInner {
1447        seed: seed.fork("numerators"),
1448        mean_numerator_bits_numerator,
1449        mean_numerator_bits_denominator,
1450        a: a.clone(),
1451        b: b.clone(),
1452        denominators: IteratorCache::new(Rational::denominators_in_closed_interval(a, b)),
1453        denominator_map: HashMap::new(),
1454        indices: geometric_random_unsigneds(
1455            seed.fork("indices"),
1456            mean_denominator_index_numerator,
1457            mean_denominator_index_denominator,
1458        ),
1459    })
1460}
1461
1462/// Generates striped random [`Rational`]s greater than or equal to a lower bound. See
1463/// [`striped_random_rational_range_to_infinity`] for more details.
1464#[derive(Clone, Debug)]
1465pub struct StripedRandomRationalRangeToInfinity {
1466    a: Rational,
1467    xs: StripedBitSource,
1468    range_generator: VariableRangeGenerator,
1469    mean_bits_numerator: u64,
1470    mean_bits_denominator: u64,
1471    denominators: StripedRandomNaturals<GeometricRandomNaturalValues<u64>>,
1472}
1473
1474impl Iterator for StripedRandomRationalRangeToInfinity {
1475    type Item = Rational;
1476
1477    fn next(&mut self) -> Option<Rational> {
1478        let d = self.denominators.next().unwrap();
1479        let numerator_bound = Integer::rounding_from(&self.a * Rational::from(&d), Ceiling).0;
1480        let (numerator, denominator) = (Rational::from(d.significant_bits())
1481            + Rational::from_unsigneds(self.mean_bits_numerator, self.mean_bits_denominator))
1482        .into_numerator_and_denominator();
1483        let numerator = u64::exact_from(&numerator);
1484        let denominator = u64::exact_from(&denominator);
1485        loop {
1486            let n = get_striped_random_integer_from_range_to_infinity(
1487                &mut self.xs,
1488                &mut self.range_generator,
1489                numerator_bound.clone(),
1490                numerator,
1491                denominator,
1492            );
1493            if n.unsigned_abs_ref().coprime_with(&d) {
1494                return Some(Rational {
1495                    sign: n >= 0,
1496                    numerator: n.unsigned_abs(),
1497                    denominator: d,
1498                });
1499            }
1500        }
1501    }
1502}
1503
1504/// Generates striped random [`Rational`]s greater than or equal to a lower bound $a$.
1505///
1506/// The actual numerator and denominator bit lengths are chosen from a geometric distribution with
1507/// mean $m$, where $m$ is `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than
1508/// `1`. A striped bit sequence with the given stripe parameter is generated and truncated at the
1509/// bit lengths to produce the numerators and denominators. The highest bits are forced to be `1`.
1510/// Finally, the [`Rational`] is reduced.
1511///
1512/// The output length is infinite.
1513///
1514/// See [`StripedBitSource`] for information about generating striped random numbers.
1515///
1516/// # Expected complexity per iteration
1517/// $T(n) = O(n (\log n)^2 \log\log n)$
1518///
1519/// $M(n) = O(n \log n)$
1520///
1521/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
1522/// mean_numerator_bits_denominator`.
1523///
1524/// # Panics
1525/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
1526/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a >
1527/// 0$ and their ratio is less than or equal to the bit length of $a$, or if they are too large and
1528/// manipulating them leads to arithmetic overflow.
1529///
1530/// # Examples
1531/// ```
1532/// use malachite_base::iterators::prefix_to_string;
1533/// use malachite_base::random::EXAMPLE_SEED;
1534/// use malachite_q::random::striped_random_rational_range_to_infinity;
1535/// use malachite_q::Rational;
1536///
1537/// assert_eq!(
1538///     prefix_to_string(
1539///         striped_random_rational_range_to_infinity(
1540///             EXAMPLE_SEED,
1541///             Rational::from_signeds(-3i32, 2),
1542///             10,
1543///             1,
1544///             3,
1545///             1
1546///         ),
1547///         10
1548///     ),
1549///     "[3/2, 39, 239/2, -32/63, 127/16, 16383/4, -1/2, 1, 583664, 1, ...]"
1550/// )
1551/// ```
1552pub fn striped_random_rational_range_to_infinity(
1553    seed: Seed,
1554    a: Rational,
1555    mean_stripe_numerator: u64,
1556    mean_stripe_denominator: u64,
1557    mean_bits_numerator: u64,
1558    mean_bits_denominator: u64,
1559) -> StripedRandomRationalRangeToInfinity {
1560    StripedRandomRationalRangeToInfinity {
1561        a,
1562        xs: StripedBitSource::new(
1563            seed.fork("xs"),
1564            mean_stripe_numerator,
1565            mean_stripe_denominator,
1566        ),
1567        range_generator: VariableRangeGenerator::new(seed.fork("range generator")),
1568        mean_bits_numerator,
1569        mean_bits_denominator,
1570        denominators: striped_random_positive_naturals(
1571            seed.fork("denominators"),
1572            mean_stripe_numerator,
1573            mean_stripe_denominator,
1574            mean_bits_numerator,
1575            mean_bits_denominator,
1576        ),
1577    }
1578}
1579
1580/// Generates random striped [`Rational`]s less than or equal to a lower bound. See
1581/// [`striped_random_rational_range_to_negative_infinity`] for more details.
1582#[derive(Clone, Debug)]
1583pub struct StripedRandomRationalRangeToNegativeInfinity {
1584    a: Rational,
1585    xs: StripedBitSource,
1586    range_generator: VariableRangeGenerator,
1587    mean_bits_numerator: u64,
1588    mean_bits_denominator: u64,
1589    denominators: StripedRandomNaturals<GeometricRandomNaturalValues<u64>>,
1590}
1591
1592impl Iterator for StripedRandomRationalRangeToNegativeInfinity {
1593    type Item = Rational;
1594
1595    fn next(&mut self) -> Option<Rational> {
1596        let d = self.denominators.next().unwrap();
1597        let numerator_bound = Integer::rounding_from(&self.a * Rational::from(&d), Floor).0;
1598        let (numerator, denominator) = (Rational::from(d.significant_bits())
1599            + Rational::from_unsigneds(self.mean_bits_numerator, self.mean_bits_denominator))
1600        .into_numerator_and_denominator();
1601        let numerator = u64::exact_from(&numerator);
1602        let denominator = u64::exact_from(&denominator);
1603        loop {
1604            let n = get_striped_random_integer_from_range_to_negative_infinity(
1605                &mut self.xs,
1606                &mut self.range_generator,
1607                numerator_bound.clone(),
1608                numerator,
1609                denominator,
1610            );
1611            if n.unsigned_abs_ref().coprime_with(&d) {
1612                return Some(Rational {
1613                    sign: n >= 0,
1614                    numerator: n.unsigned_abs(),
1615                    denominator: d,
1616                });
1617            }
1618        }
1619    }
1620}
1621
1622/// Generates striped random [`Rational`]s less than or equal to a lower bound $a$.
1623///
1624/// The actual numerator and denominator bit lengths are chosen from a geometric distribution with
1625/// mean $m$, where $m$ is `mean_bits_numerator / mean_bits_denominator`; $m$ must be greater than
1626/// `1`. A striped bit sequence with the given stripe parameter is generated and truncated at the
1627/// bit lengths to produce the numerators and denominators. The highest bits are forced to be `1`.
1628/// Finally, the [`Rational`] is reduced.
1629///
1630/// The output length is infinite.
1631///
1632/// See [`StripedBitSource`] for information about generating striped random numbers.
1633///
1634/// # Expected complexity per iteration
1635/// $T(n) = O(n (\log n)^2 \log\log n)$
1636///
1637/// $M(n) = O(n \log n)$
1638///
1639/// where $T$ is time, $M$ is additional memory, and $n$ is `mean_numerator_bits_numerator /
1640/// mean_numerator_bits_denominator`.
1641///
1642/// # Panics
1643/// Panics if `mean_stripe_denominator` is zero, if `mean_stripe_numerator <
1644/// mean_stripe_denominator`, if `mean_bits_numerator` or `mean_bits_denominator` are zero, if $a <
1645/// 0$ and their ratio is less than or equal to the bit length of $a$, or if they are too large and
1646/// manipulating them leads to arithmetic overflow.
1647///
1648/// # Examples
1649/// ```
1650/// use malachite_base::iterators::prefix_to_string;
1651/// use malachite_base::random::EXAMPLE_SEED;
1652/// use malachite_q::random::striped_random_rational_range_to_negative_infinity;
1653/// use malachite_q::Rational;
1654///
1655/// assert_eq!(
1656///     prefix_to_string(
1657///         striped_random_rational_range_to_negative_infinity(
1658///             EXAMPLE_SEED,
1659///             Rational::from_signeds(-3i32, 2),
1660///             10,
1661///             1,
1662///             3,
1663///             1
1664///         ),
1665///         10
1666///     ),
1667///     "[-79/2, -7, -1051/2, -95/63, -255/16, -159/4, -3/2, -16, -2, -22, ...]"
1668/// )
1669/// ```
1670pub fn striped_random_rational_range_to_negative_infinity(
1671    seed: Seed,
1672    a: Rational,
1673    mean_stripe_numerator: u64,
1674    mean_stripe_denominator: u64,
1675    mean_bits_numerator: u64,
1676    mean_bits_denominator: u64,
1677) -> StripedRandomRationalRangeToNegativeInfinity {
1678    StripedRandomRationalRangeToNegativeInfinity {
1679        a,
1680        xs: StripedBitSource::new(
1681            seed.fork("xs"),
1682            mean_stripe_numerator,
1683            mean_stripe_denominator,
1684        ),
1685        range_generator: VariableRangeGenerator::new(seed.fork("range generator")),
1686        mean_bits_numerator,
1687        mean_bits_denominator,
1688        denominators: striped_random_positive_naturals(
1689            seed.fork("denominators"),
1690            mean_stripe_numerator,
1691            mean_stripe_denominator,
1692            mean_bits_numerator,
1693            mean_bits_denominator,
1694        ),
1695    }
1696}