qfall_math/integer/z/sample/binomial.rs
1// Copyright 2023 Jan Niklas Siemer
2//
3// This file is part of qFALL-math.
4//
5// qFALL-math is free software: you can redistribute it and/or modify it under
6// the terms of the Mozilla Public License Version 2.0 as published by the
7// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.
8
9//! This module contains algorithms for sampling
10//! according to the binomial distribution.
11
12use crate::{
13 error::MathError, integer::Z, macros::seeded::seedable_function, rational::Q,
14 utils::sample::binomial::BinomialSampler,
15};
16
17impl Z {
18 seedable_function!(
19 /// Chooses a [`Z`] instance according to the binomial distribution
20 /// parameterized by `n` and `p`.
21 ///
22 /// Parameters:
23 /// - `n`: specifies the number of trials
24 /// - `p`: specifies the probability of success
25 #[seeded]
26 /// - `seed`: specifies the 256-bit seed of the PRNG used for sampling
27 #[optionally_seeded]
28 /// - `seed`: specifies an optional 256-bit seed of the PRNG used for sampling.
29 #[optionally_seeded]
30 /// If `None` is provided, a fresh [`ThreadRng`](rand::rngs::ThreadRng) is used instead.
31 ///
32 /// Returns a fresh [`Z`] instance with a value sampled
33 /// according to the binomial distribution or a [`MathError`]
34 /// if `n < 0`, `p ∉ (0,1)`, or `n` does not fit into an [`i64`].
35 ///
36 /// # Examples
37 /// ```
38 /// use qfall_math::integer::Z;
39 ///
40 #[unseeded]
41 /// let sample = Z::sample_binomial(2, 0.5).unwrap();
42 #[seeded]
43 /// let sample = Z::sample_binomial_seeded(2, 0.5, [42; 32]).unwrap();
44 /// ```
45 ///
46 /// # Errors and Failures
47 /// - Returns a [`MathError`] of type [`InvalidIntegerInput`](MathError::InvalidIntegerInput)
48 /// if `n < 0`.
49 /// - Returns a [`MathError`] of type [`InvalidInterval`](MathError::InvalidInterval)
50 /// if `p ∉ (0,1)`.
51 /// - Returns a [`MathError`] of type [`ConversionError`](MathError::ConversionError)
52 /// if `n` does not fit into an [`i64`].
53 pub(crate) fn sample_binomial(
54 n: impl Into<Z>,
55 p: impl Into<Q>,
56 seed: Option<[u8; 32]>,
57 ) -> Result<Self, MathError> {
58 let mut bin_sampler = BinomialSampler::init(n, p, seed)?;
59
60 Ok(bin_sampler.sample())
61 }
62 );
63}
64
65#[cfg(test)]
66mod test_sample_binomial {
67 use super::{Q, Z};
68 use crate::utils::sample::test_seed;
69
70 // As all major tests regarding an appropriate binomial distribution,
71 // whether the correct interval is kept, and if the errors are thrown correctly,
72 // are performed in the `utils` module, we omit these tests here.
73
74 /// Checks whether `sample_binomial` is available for all types
75 /// implementing [`Into<Z>`], i.e. u8, u16, u32, u64, i8, ...
76 /// and [`Into<Q>`], i.e. u8, u16, i8, i16, f32, f64, ...
77 #[test]
78 fn availability() {
79 for seeded in [false, true] {
80 let _ = Z::sample_binomial_optionally_seeded(1u16, 7u8, seeded.then(test_seed));
81 let _ = Z::sample_binomial_optionally_seeded(1u32, 7u16, seeded.then(test_seed));
82 let _ = Z::sample_binomial_optionally_seeded(1u64, 7u32, seeded.then(test_seed));
83 let _ = Z::sample_binomial_optionally_seeded(1i8, 7u64, seeded.then(test_seed));
84 let _ = Z::sample_binomial_optionally_seeded(1i16, 7i8, seeded.then(test_seed));
85 let _ = Z::sample_binomial_optionally_seeded(1i32, 7i16, seeded.then(test_seed));
86 let _ = Z::sample_binomial_optionally_seeded(1i64, 7i32, seeded.then(test_seed));
87 let _ = Z::sample_binomial_optionally_seeded(Z::ONE, 7i64, seeded.then(test_seed));
88 let _ = Z::sample_binomial_optionally_seeded(1u8, 0.5f32, seeded.then(test_seed));
89 let _ = Z::sample_binomial_optionally_seeded(1u8, 0.5f64, seeded.then(test_seed));
90 let _ =
91 Z::sample_binomial_optionally_seeded(1, Q::from((1, 2)), seeded.then(test_seed));
92
93 // explicitly checks the existence of the unseeded and the seeded function
94 if seeded {
95 let _ = Z::sample_binomial_seeded(1u16, 7u8, test_seed());
96 } else {
97 let _ = Z::sample_binomial(1u16, 7u8);
98 }
99 }
100 }
101
102 /// Checks whether the same seed results in the same sample.
103 #[test]
104 fn same_seed_same_sample() {
105 use crate::integer::Z;
106 let sample_0 = Z::sample_binomial_seeded(2, 0.5, [42; 32]).unwrap();
107 let sample_1 = Z::sample_binomial_seeded(2, 0.5, [42; 32]).unwrap();
108
109 assert_eq!(sample_0, sample_1);
110 }
111
112 /// Checks whether the seeded variant outputs the known sample for a fixed seed.
113 #[test]
114 fn known_answer() {
115 use crate::integer::Z;
116 let sample = Z::sample_binomial_seeded(2, 0.5, [42; 32]).unwrap();
117
118 assert_eq!("0", sample.to_string());
119 }
120}