rgsl/types/rng.rs
1//
2// A rust binding for the GSL library by Guillaume Gomez (guillaume1.gomez@gmail.com)
3//
4
5/*!
6# Random Number Generation
7
8The library provides a large collection of random number generators which can be accessed through a uniform interface.
9Environment variables allow you to select different generators and seeds at runtime, so that you can easily switch between generators without needing to recompile your program.
10Each instance of a generator keeps track of its own state, allowing the generators to be used in multi-threaded programs.
11Additional functions are available for transforming uniform random numbers into samples from continuous or discrete probability distributions such as the Gaussian, log-normal or Poisson distributions.
12
13## General comments on random numbers
14
15In 1988, Park and Miller wrote a paper entitled “Random number generators: good ones are hard to find.” [Commun. ACM, 31, 1192–1201]. Fortunately, some excellent random number generators are available, though poor ones are still in common use. You may be happy with the system-supplied random number generator on your computer, but you should be aware that as computers get faster, requirements on random number generators increase. Nowadays, a simulation that calls a random number generator millions of times can often finish before you can make it down the hall to the coffee machine and back.
16
17A very nice review of random number generators was written by Pierre L’Ecuyer, as Chapter 4 of the book: Handbook on Simulation, Jerry Banks, ed. (Wiley, 1997). The chapter is available in postscript from L’Ecuyer’s ftp site (see references). Knuth’s volume on Seminumerical Algorithms (originally published in 1968) devotes 170 pages to random number generators, and has recently been updated in its 3rd edition (1997). It is brilliant, a classic. If you don’t own it, you should stop reading right now, run to the nearest bookstore, and buy it.
18
19A good random number generator will satisfy both theoretical and statistical properties. Theoretical properties are often hard to obtain (they require real math!), but one prefers a random number generator with a long period, low serial correlation, and a tendency not to “fall mainly on the planes.” Statistical tests are performed with numerical simulations. Generally, a random number generator is used to estimate some quantity for which the theory of probability provides an exact answer. Comparison to this exact answer provides a measure of “randomness”.
20
21## The Random Number Generator Interface
22
23It is important to remember that a random number generator is not a “real” function like sine or cosine. Unlike real functions, successive calls to a random number generator yield different return values. Of course that is just what you want for a random number generator, but to achieve this effect, the generator must keep track of some kind of “state” variable.
24Sometimes this state is just an integer (sometimes just the value of the previously generated random number), but often it is more complicated than that and may involve a whole array of numbers, possibly with some indices thrown in. To use the random number generators, you do not need to know the details of what comprises the state, and besides that varies from algorithm to algorithm.
25
26The random number generator library uses two special structs, RngType which holds static information about each type of generator and Rng which describes an instance of a generator created from a given RngType.
27
28## Performance
29
30The following table shows the relative performance of a selection the available random number generators. The fastest simulation quality generators are taus, gfsr4 and mt19937. The generators which offer the best mathematically-proven quality are those based on the RANLUX algorithm.
31
32 * 1754 k ints/sec, 870 k doubles/sec, taus
33 * 1613 k ints/sec, 855 k doubles/sec, gfsr4
34 * 1370 k ints/sec, 769 k doubles/sec, mt19937
35 * 565 k ints/sec, 571 k doubles/sec, ranlxs0
36 * 400 k ints/sec, 405 k doubles/sec, ranlxs1
37 * 490 k ints/sec, 389 k doubles/sec, mrg
38 * 407 k ints/sec, 297 k doubles/sec, ranlux
39 * 243 k ints/sec, 254 k doubles/sec, ranlxd1
40 * 251 k ints/sec, 253 k doubles/sec, ranlxs2
41 * 238 k ints/sec, 215 k doubles/sec, cmrg
42 * 247 k ints/sec, 198 k doubles/sec, ranlux389
43 * 141 k ints/sec, 140 k doubles/sec, ranlxd2
44
45## Random number environment variables
46
47The library allows you to choose a default generator and seed from the environment variables GSL_RNG_TYPE and GSL_RNG_SEED and the function gsl_rng_env_setup. This makes it easy try out different generators and seeds without having to recompile your program.
48
49## References and Further Reading
50
51The subject of random number generation and testing is reviewed extensively in Knuth’s Seminumerical Algorithms.
52
53Donald E. Knuth, The Art of Computer Programming: Seminumerical Algorithms (Vol 2, 3rd Ed, 1997), Addison-Wesley, ISBN 0201896842.
54Further information is available in the review paper written by Pierre L’Ecuyer,
55
56P. L’Ecuyer, “Random Number Generation”, Chapter 4 of the Handbook on Simulation, Jerry Banks Ed., Wiley, 1998, 93–137.
57http://www.iro.umontreal.ca/~lecuyer/papers.html
58
59The source code for the DIEHARD random number generator tests is also available online,
60
61DIEHARD source code G. Marsaglia,
62http://stat.fsu.edu/pub/diehard/
63A comprehensive set of random number generator tests is available from NIST,
64
65NIST Special Publication 800-22, “A Statistical Test Suite for the Validation of Random Number Generators and Pseudo Random Number Generators for Cryptographic Applications”.
66http://csrc.nist.gov/rng/
67
68## Acknowledgements
69
70Thanks to Makoto Matsumoto, Takuji Nishimura and Yoshiharu Kurita for making the source code to their generators (MT19937, MM&TN; TT800, MM&YK) available under the GNU General Public License. Thanks to Martin Lüscher for providing notes and source code for the RANLXS and RANLXD generators.
71!*/
72
73use crate::Value;
74use ffi::FFI;
75use std::os::raw::c_ulong;
76
77ffi_wrapper!(Rng, *mut sys::gsl_rng, gsl_rng_free);
78
79impl Rng {
80 /// This function returns a pointer to a newly-created instance of a random number generator of type T. For example, the following code creates an instance of the Tausworthe generator,
81 ///
82 /// ```Rust
83 /// let r = Rng::new(gsl_rng_taus);
84 /// ```
85 ///
86 /// If there is insufficient memory to create the generator then the function returns a null pointer and the error handler is invoked with an error code of GSL_ENOMEM.
87 ///
88 /// The generator is automatically initialized with the default seed, gsl_rng_default_seed. This is zero by default but can be changed either directly or by using the environment variable
89 /// GSL_RNG_SEED (see [`Random number environment variables`](https://www.gnu.org/software/gsl/manual/html_node/Random-number-environment-variables.html#Random-number-environment-variables)).
90 #[doc(alias = "gsl_rng_alloc")]
91 pub fn new(T: RngType) -> Option<Rng> {
92 let tmp = unsafe { sys::gsl_rng_alloc(T.unwrap_shared()) };
93
94 if tmp.is_null() {
95 None
96 } else {
97 Some(Rng::wrap(tmp))
98 }
99 }
100
101 /// This function initializes (or ‘seeds’) the random number generator. If the generator is seeded with the same value of s on two different runs, the same stream of random numbers will be generated by successive calls to the routines below.
102 /// If different values of s >= 1 are supplied, then the generated streams of random numbers should be completely different. If the seed s is zero then the standard seed from the original implementation is used instead.
103 /// For example, the original Fortran source code for the ranlux generator used a seed of 314159265, and so choosing s equal to zero reproduces this when using gsl_rng_ranlux.
104 ///
105 /// When using multiple seeds with the same generator, choose seed values greater than zero to avoid collisions with the default setting.
106 ///
107 /// Note that the most generators only accept 32-bit seeds, with higher values being reduced modulo 2^32. For generators with smaller ranges the maximum seed value will typically be lower.
108 #[doc(alias = "gsl_rng_set")]
109 pub fn set(&mut self, s: usize) {
110 unsafe { sys::gsl_rng_set(self.unwrap_unique(), s as _) }
111 }
112
113 /// This function returns a random integer from the generator r. The minimum and maximum values depend on the algorithm used, but all integers in the range [min,max] are equally likely.
114 /// The values of min and max can be determined using the auxiliary functions gsl_rng_max (r) and gsl_rng_min (r).
115 #[doc(alias = "gsl_rng_get")]
116 pub fn get(&mut self) -> usize {
117 unsafe { sys::gsl_rng_get(self.unwrap_shared()) as _ }
118 }
119
120 /// This function returns a double precision floating point number uniformly distributed in the range [0,1). The range includes 0.0 but excludes 1.0.
121 /// The value is typically obtained by dividing the result of gsl_rng_get(r) by gsl_rng_max(r) + 1.0 in double precision.
122 /// Some generators compute this ratio internally so that they can provide floating point numbers with more than 32 bits of randomness (the maximum number of bits that can be portably represented in a single unsigned long int).
123 #[doc(alias = "gsl_rng_uniform")]
124 pub fn uniform(&mut self) -> f64 {
125 unsafe { sys::gsl_rng_uniform(self.unwrap_unique()) }
126 }
127
128 /// This function returns a positive double precision floating point number uniformly distributed in the range (0,1), excluding both 0.0 and 1.0.
129 /// The number is obtained by sampling the generator with the algorithm of gsl_rng_uniform until a non-zero value is obtained.
130 /// You can use this function if you need to avoid a singularity at 0.0.
131 #[doc(alias = "gsl_rng_uniform_pos")]
132 pub fn uniform_pos(&mut self) -> f64 {
133 unsafe { sys::gsl_rng_uniform_pos(self.unwrap_unique()) }
134 }
135
136 /// This function returns a random integer from 0 to n-1 inclusive by scaling down and/or discarding samples from the generator r.
137 /// All integers in the range [0,n-1] are produced with equal probability. For generators with a non-zero minimum value an offset is applied so that zero is returned with the correct probability.
138 ///
139 /// Note that this function is designed for sampling from ranges smaller than the range of the underlying generator. The parameter n must be less than or equal to the range of the generator r.
140 /// If n is larger than the range of the generator then the function calls the error handler with an error code of GSL_EINVAL and returns zero.
141 ///
142 /// In particular, this function is not intended for generating the full range of unsigned integer values [0,2^32-1].
143 /// Instead choose a generator with the maximal integer range and zero minimum value, such as gsl_rng_ranlxd1, gsl_rng_mt19937 or gsl_rng_taus, and sample it directly using gsl_rng_get. The range of each generator can be found using the auxiliary functions described in the next section.
144 #[doc(alias = "gsl_rng_uniform_int")]
145 pub fn uniform_int(&mut self, n: usize) -> usize {
146 unsafe { sys::gsl_rng_uniform_int(self.unwrap_unique(), n as c_ulong) as _ }
147 }
148
149 /// This function returns a pointer to the name of the generator. For example,
150 ///
151 /// ```Rust
152 /// println!("r is a '{}' generator", r.get_name());
153 /// ```
154 ///
155 /// would print something like "r is a 'taus' generator".
156 #[doc(alias = "gsl_rng_name")]
157 pub fn name(&self) -> String {
158 unsafe {
159 let tmp = sys::gsl_rng_name(self.unwrap_shared());
160
161 String::from_utf8_lossy(::std::ffi::CStr::from_ptr(tmp).to_bytes()).to_string()
162 }
163 }
164
165 /// This function returns the largest value that the get function can return.
166 #[doc(alias = "gsl_rng_max")]
167 pub fn max(&self) -> usize {
168 unsafe { sys::gsl_rng_max(self.unwrap_shared()) as _ }
169 }
170
171 /// This function returns the smallest value that gsl_rng_get can return. Usually this value is zero.
172 /// There are some generators with algorithms that cannot return zero, and for these generators the minimum value is 1.
173 #[doc(alias = "gsl_rng_min")]
174 pub fn min(&self) -> usize {
175 unsafe { sys::gsl_rng_min(self.unwrap_shared()) as _ }
176 }
177
178 /// This function returns a pointer to the state of generator r. You can use this information
179 /// to access the state directly. For example, the following code will write the state of a
180 /// generator to a stream,
181 ///
182 /// ```C
183 /// void * state = gsl_rng_state (r);
184 /// size_t n = gsl_rng_size (r);
185 /// fwrite (state, n, 1, stream);
186 /// ```
187 #[doc(alias = "gsl_rng_state")]
188 pub fn state<T>(&self) -> &T {
189 unsafe { &(*(sys::gsl_rng_state(self.unwrap_shared()) as *const T)) }
190 }
191
192 /// This function returns a pointer to the state of generator r. You can use this information
193 /// to access the state directly. For example, the following code will write the state of a
194 /// generator to a stream,
195 ///
196 /// ```C
197 /// void * state = gsl_rng_state (r);
198 /// size_t n = gsl_rng_size (r);
199 /// fwrite (state, n, 1, stream);
200 /// ```
201 // checker:ignore
202 #[doc(alias = "gsl_rng_state")]
203 pub fn state_mut<T>(&mut self) -> &mut T {
204 unsafe { &mut (*(sys::gsl_rng_state(self.unwrap_shared()) as *mut T)) }
205 }
206
207 /// This function copies the random number generator src into the pre-existing generator dest, making dest into an exact copy of src. The two generators must be of the same type.
208 #[doc(alias = "gsl_rng_memcpy")]
209 pub fn copy(&self, other: &mut Rng) -> Result<(), Value> {
210 let ret = unsafe { sys::gsl_rng_memcpy(other.unwrap_unique(), self.unwrap_shared()) };
211 result_handler!(ret, ())
212 }
213
214 /// This function returns the size of the state of generator r. You can use this information to access the state directly. For example, the following code will write the state of a generator to a stream,
215 ///
216 /// ```C
217 /// void * state = gsl_rng_state (r);
218 /// size_t n = gsl_rng_size (r);
219 /// fwrite (state, n, 1, stream);
220 /// ```
221 #[doc(alias = "gsl_rng_size")]
222 pub fn size(&self) -> usize {
223 unsafe { sys::gsl_rng_size(self.unwrap_shared()) }
224 }
225
226 /// Equivalent to DefaultRngSeed
227 pub fn default_seed() -> usize {
228 unsafe { sys::gsl_rng_default_seed as _ }
229 }
230
231 /// This function randomly shuffles the order of n objects, each of size size, stored in the array base[0..n-1]. The output of the random number generator r is used to
232 /// produce the permutation. The algorithm generates all possible n! permutations with equal probability, assuming a perfect source of random numbers.
233 ///
234 /// The following code shows how to shuffle the numbers from 0 to 51,
235 ///
236 /// ```C
237 /// int a[52];
238 ///
239 /// for (i = 0; i < 52; i++)
240 /// {
241 /// a[i] = i;
242 /// }
243 ///
244 /// gsl_ran_shuffle (r, a, 52, sizeof (int));
245 /// ```
246 #[doc(alias = "gsl_ran_shuffle")]
247 pub fn shuffle<T>(&mut self, base: &mut [T]) {
248 unsafe {
249 sys::gsl_ran_shuffle(
250 self.unwrap_unique(),
251 base.as_mut_ptr() as *mut _,
252 base.len() as _,
253 std::mem::size_of::<T>() as _,
254 )
255 }
256 }
257
258 /// This function fills the array `dest[k]` with k objects taken randomly from the n elements of the array `src[0..n-1]`. The objects are each of size size.
259 /// The output of the random number generator r is used to make the selection. The algorithm ensures all possible samples are equally likely, assuming a perfect source of randomness.
260 ///
261 /// The objects are sampled without replacement, thus each object can only appear once in `dest[k]`. It is required that k be less than or equal to n.
262 /// The objects in dest will be in the same relative order as those in src. You will need to call gsl_ran_shuffle(r, dest, n, size) if you want to randomize the order.
263 ///
264 /// The following code shows how to select a random sample of three unique numbers from the set 0 to 99,
265 ///
266 /// ```C
267 /// double a[3], b[100];
268 ///
269 /// for (i = 0; i < 100; i++)
270 /// {
271 /// b[i] = (double) i;
272 /// }
273 ///
274 /// gsl_ran_choose (r, a, 3, b, 100, sizeof (double));
275 /// ```
276 #[doc(alias = "gsl_ran_choose")]
277 pub fn choose<T>(&mut self, src: &[T], dest: &mut [T]) -> Result<(), Value> {
278 assert!(src.len() <= dest.len());
279 let ret = unsafe {
280 sys::gsl_ran_choose(
281 self.unwrap_unique(),
282 dest.as_mut_ptr() as *mut _,
283 dest.len() as _,
284 src.as_ptr() as *mut _,
285 src.len() as _,
286 std::mem::size_of::<T>() as _,
287 )
288 };
289 result_handler!(ret, ())
290 }
291
292 /// This function is like gsl_ran_choose but samples k items from the original array of n items src with replacement, so the same object can appear more
293 /// than once in the output sequence dest. There is no requirement that k be less than n in this case.
294 #[doc(alias = "gsl_ran_sample")]
295 pub fn sample<T>(&mut self, src: &[T], dest: &mut [T]) {
296 assert!(src.len() <= dest.len());
297 unsafe {
298 sys::gsl_ran_sample(
299 self.unwrap_unique(),
300 dest.as_mut_ptr() as *mut _,
301 dest.len() as _,
302 src.as_ptr() as *mut _,
303 src.len() as _,
304 std::mem::size_of::<T>() as _,
305 )
306 }
307 }
308
309 /// This function computes a random sample n[] from the multinomial distribution formed by N trials from an underlying distribution `p[K]`. The distribution function for `n[]` is,
310 ///
311 /// ```text
312 /// P(n_1, n_2, ..., n_K) =
313 /// (N!/(n_1! n_2! ... n_K!)) p_1^n_1 p_2^n_2 ... p_K^n_K
314 /// ```
315 ///
316 /// where (n_1, n_2, ..., n_K) are nonnegative integers with
317 /// `sum_{k=1}^K n_k = N, and (p_1, p_2, ..., p_K)` is a probability distribution with
318 /// `\sum p_i = 1`. If the array `p[K]` is not normalized then its entries will be treated
319 /// as weights and normalized appropriately. The arrays `n[]` and `p[]` must both be of length K.
320 ///
321 /// Random variates are generated using the conditional binomial method (see C.S. Davis, The computer generation of multinomial random variates, Comp. Stat. Data Anal. 16 (1993) 205–217 for details).
322 #[doc(alias = "gsl_ran_multinomial")]
323 pub fn multinomial(&mut self, N: u32, p: &[f64], n: &mut [u32]) {
324 assert!(p.len() <= n.len());
325 unsafe {
326 sys::gsl_ran_multinomial(
327 self.unwrap_unique(),
328 p.len() as _,
329 N,
330 p.as_ptr(),
331 n.as_mut_ptr(),
332 )
333 }
334 }
335
336 /// This function returns an array of K random variates from a Dirichlet distribution of order K-1. The distribution function is
337 ///
338 /// p(\theta_1, ..., \theta_K) d\theta_1 ... d\theta_K =
339 ///
340 /// (1/Z) \prod_{i=1}^K \theta_i^{\alpha_i - 1} \delta(1 -\sum_{i=1}^K \theta_i) d\theta_1 ... d\theta_K
341 ///
342 /// for theta_i >= 0 and alpha_i > 0. The delta function ensures that \sum \theta_i = 1. The normalization factor Z is
343 ///
344 /// Z = {\prod_{i=1}^K \Gamma(\alpha_i)} / {\Gamma( \sum_{i=1}^K \alpha_i)}
345 ///
346 /// The random variates are generated by sampling K values from gamma distributions with parameters a=alpha_i, b=1, and renormalizing. See A.M. Law, W.D. Kelton, Simulation Modeling and Analysis (1991).
347 #[doc(alias = "gsl_ran_dirichlet")]
348 pub fn dirichlet(&mut self, alpha: &[f64], theta: &mut [f64]) {
349 assert!(alpha.len() <= theta.len());
350 unsafe {
351 sys::gsl_ran_dirichlet(
352 self.unwrap_unique(),
353 alpha.len() as _,
354 alpha.as_ptr(),
355 theta.as_mut_ptr(),
356 )
357 }
358 }
359
360 /// This function returns either 0 or 1, the result of a Bernoulli trial with probability p. The probability distribution for a Bernoulli trial is,
361 ///
362 /// p(0) = 1 - p
363 /// p(1) = p
364 #[doc(alias = "gsl_ran_bernoulli")]
365 pub fn bernoulli(&mut self, p: f64) -> u32 {
366 unsafe { sys::gsl_ran_bernoulli(self.unwrap_unique(), p) }
367 }
368
369 /// This function returns a random variate from the beta distribution. The distribution function is,
370 ///
371 /// p(x) dx = {Gamma(a+b) over Gamma(a) Gamma(b)} x^{a-1} (1-x)^{b-1} dx
372 ///
373 /// for 0 <= x <= 1.
374 #[doc(alias = "gsl_ran_beta")]
375 pub fn beta(&mut self, a: f64, b: f64) -> f64 {
376 unsafe { sys::gsl_ran_beta(self.unwrap_unique(), a, b) }
377 }
378
379 /// This function returns a random integer from the binomial distribution, the number of successes in n independent trials with probability p. The probability distribution for binomial variates is,
380 ///
381 /// p(k) = {n! \over k! (n-k)! } p^k (1-p)^{n-k}
382 ///
383 /// for 0 <= k <= n.
384 #[doc(alias = "gsl_ran_binomial")]
385 pub fn binomial(&mut self, p: f64, n: u32) -> u32 {
386 unsafe { sys::gsl_ran_binomial(self.unwrap_unique(), p, n) }
387 }
388
389 /// This function generates a pair of correlated Gaussian variates, with mean zero, correlation coefficient rho and standard deviations sigma_x and sigma_y in the x and y directions.
390 /// The probability distribution for bivariate Gaussian random variates is,
391 ///
392 /// p(x,y) dx dy = {1 \over 2 \pi \sigma_x \sigma_y \sqrt{1-\rho^2}} \exp (-(x^2/\sigma_x^2 + y^2/\sigma_y^2 - 2 \rho x y/(\sigma_x\sigma_y))/2(1-\rho^2)) dx dy
393 ///
394 /// for x,y in the range -\infty to +\infty. The correlation coefficient rho should lie between 1 and -1.
395 #[doc(alias = "gsl_ran_bivariate_gaussian")]
396 pub fn bivariate_gaussian(&mut self, sigma_x: f64, sigma_y: f64, rho: f64) -> (f64, f64) {
397 let mut x = 0.;
398 let mut y = 0.;
399
400 unsafe {
401 sys::gsl_ran_bivariate_gaussian(
402 self.unwrap_unique(),
403 sigma_x,
404 sigma_y,
405 rho,
406 &mut x,
407 &mut y,
408 );
409 }
410 (x, y)
411 }
412
413 /// This function returns a random variate from the Cauchy distribution with scale parameter a. The probability distribution for Cauchy random variates is,
414 ///
415 /// p(x) dx = {1 \over a\pi (1 + (x/a)^2) } dx
416 ///
417 /// for x in the range -\infty to +\infty. The Cauchy distribution is also known as the Lorentz distribution.
418 #[doc(alias = "gsl_ran_cauchy")]
419 pub fn cauchy(&mut self, a: f64) -> f64 {
420 unsafe { sys::gsl_ran_cauchy(self.unwrap_unique(), a) }
421 }
422
423 /// This function returns a random variate from the chi-squared distribution with nu degrees of freedom. The distribution function is,
424 ///
425 /// p(x) dx = {1 \over 2 Gamma(\nu/2) } (x/2)^{\nu/2 - 1} \exp(-x/2) dx
426 ///
427 /// for x >= 0.
428 #[doc(alias = "gsl_ran_chisq")]
429 pub fn chisq(&mut self, nu: f64) -> f64 {
430 unsafe { sys::gsl_ran_chisq(self.unwrap_unique(), nu) }
431 }
432
433 /// This function returns a random variate from the exponential distribution with mean mu. The distribution is,
434 ///
435 /// p(x) dx = {1 \over \mu} \exp(-x/\mu) dx
436 ///
437 /// for x >= 0.
438 #[doc(alias = "gsl_ran_exponential")]
439 pub fn exponential(&mut self, mu: f64) -> f64 {
440 unsafe { sys::gsl_ran_exponential(self.unwrap_unique(), mu) }
441 }
442
443 /// This function returns a random variate from the exponential power distribution with scale parameter a and exponent b. The distribution is,
444 ///
445 /// p(x) dx = {1 \over 2 a Gamma(1+1/b)} \exp(-|x/a|^b) dx
446 ///
447 /// for x >= 0. For b = 1 this reduces to the Laplace distribution. For b = 2 it has the same form as a Gaussian distribution, but with a = \sqrt{2} \sigma.
448 #[doc(alias = "gsl_ran_exppow")]
449 pub fn exppow(&mut self, a: f64, b: f64) -> f64 {
450 unsafe { sys::gsl_ran_exppow(self.unwrap_unique(), a, b) }
451 }
452
453 /// This function returns a random variate from the F-distribution with degrees of freedom nu1 and nu2. The distribution function is,
454 ///
455 /// ```latex
456 /// p(x) dx =
457 /// { Gamma((\nu_1 + \nu_2)/2)
458 ///
459 /// over Gamma(nu_1/2) Gamma(nu_2/2) }
460 ///
461 /// \nu_1^{\nu_1/2} \nu_2^{\nu_2/2}
462 ///
463 /// x^{\nu_1/2 - 1} (\nu_2 + \nu_1 x)^{-\nu_1/2 -\nu_2/2}
464 /// ```
465 ///
466 /// for x >= 0.
467 #[doc(alias = "gsl_ran_fdist")]
468 pub fn fdist(&mut self, nu1: f64, nu2: f64) -> f64 {
469 unsafe { sys::gsl_ran_fdist(self.unwrap_unique(), nu1, nu2) }
470 }
471
472 /// This function returns a random variate from the flat (uniform) distribution from a to b. The distribution is,
473 ///
474 /// p(x) dx = {1 \over (b-a)} dx
475 ///
476 /// if a <= x < b and 0 otherwise.
477 #[doc(alias = "gsl_ran_flat")]
478 pub fn flat(&mut self, a: f64, b: f64) -> f64 {
479 unsafe { sys::gsl_ran_flat(self.unwrap_unique(), a, b) }
480 }
481
482 /// This function returns a random variate from the gamma distribution. The distribution function is,
483 ///
484 /// p(x) dx = {1 over Gamma(a) b^a} x^{a-1} e^{-x/b} dx
485 ///
486 /// for x > 0.
487 ///
488 /// The gamma distribution with an integer parameter a is known as the Erlang distribution.
489 ///
490 /// The variates are computed using the Marsaglia-Tsang fast gamma method. This function for this method was previously called gsl_ran_gamma_mt and can still be accessed using this name.
491 #[doc(alias = "gsl_ran_gamma")]
492 pub fn gamma(&mut self, a: f64, b: f64) -> f64 {
493 unsafe { sys::gsl_ran_gamma(self.unwrap_unique(), a, b) }
494 }
495
496 /// This function returns a gamma variate using the algorithms from Knuth (vol 2).
497 #[doc(alias = "gsl_ran_gamma_knuth")]
498 pub fn gamma_knuth(&mut self, a: f64, b: f64) -> f64 {
499 unsafe { sys::gsl_ran_gamma_knuth(self.unwrap_unique(), a, b) }
500 }
501
502 /// This function returns a Gaussian random variate, with mean zero and standard deviation sigma.
503 /// The probability distribution for Gaussian random variates is,
504 ///
505 /// p(x) dx = {1 \over \sqrt{2 \pi \sigma^2}} \exp (-x^2 / 2\sigma^2) dx
506 /// for x in the range -\infty to +\infty. Use the transformation z = \mu + x on the numbers returned by gsl_ran_gaussian to obtain a Gaussian distribution with mean \mu.
507 /// This function uses the Box-Muller algorithm which requires two calls to the random number generator r.
508 #[doc(alias = "gsl_ran_gaussian")]
509 pub fn gaussian(&mut self, sigma: f64) -> f64 {
510 unsafe { sys::gsl_ran_gaussian(self.unwrap_unique(), sigma) }
511 }
512
513 #[doc(alias = "gsl_ran_gaussian_ziggurat")]
514 pub fn gaussian_ziggurat(&mut self, sigma: f64) -> f64 {
515 unsafe { sys::gsl_ran_gaussian_ziggurat(self.unwrap_unique(), sigma) }
516 }
517
518 /// This function computes a Gaussian random variate using the alternative Marsaglia-Tsang ziggurat and Kinderman-Monahan-Leva ratio methods.
519 /// The Ziggurat algorithm is the fastest available algorithm in most cases.
520 #[doc(alias = "gsl_ran_gaussian_ratio_method")]
521 pub fn gaussian_ratio_method(&mut self, sigma: f64) -> f64 {
522 unsafe { sys::gsl_ran_gaussian_ratio_method(self.unwrap_unique(), sigma) }
523 }
524
525 /// This function computes results for the unit Gaussian distribution.
526 /// They are equivalent to the functions above with a standard deviation of one, sigma = 1.
527 #[doc(alias = "gsl_ran_ugaussian")]
528 pub fn ugaussian(&mut self) -> f64 {
529 unsafe { sys::gsl_ran_ugaussian(self.unwrap_unique()) }
530 }
531
532 /// This function computes results for the unit Gaussian distribution.
533 /// They are equivalent to the functions above with a standard deviation of one, sigma = 1.
534 #[doc(alias = "gsl_ran_ugaussian_ratio_method")]
535 pub fn ugaussian_ratio_method(&mut self) -> f64 {
536 unsafe { sys::gsl_ran_ugaussian_ratio_method(self.unwrap_unique()) }
537 }
538
539 /// This function provides random variates from the upper tail of a Gaussian distribution with standard deviation sigma.
540 /// The values returned are larger than the lower limit a, which must be positive. The method is based on Marsaglia’s famous rectangle-wedge-tail algorithm (Ann. Math. Stat. 32, 894–899 (1961)), with this aspect explained in Knuth, v2, 3rd ed, p139,586 (exercise 11).
541 ///
542 /// The probability distribution for Gaussian tail random variates is,
543 ///
544 /// p(x) dx = {1 \over N(a;\sigma) \sqrt{2 \pi \sigma^2}} \exp (- x^2/(2 \sigma^2)) dx
545 ///
546 /// for x > a where N(a;\sigma) is the normalization constant,
547 ///
548 /// N(a;\sigma) = (1/2) erfc(a / sqrt(2 sigma^2)).
549 #[doc(alias = "gsl_ran_gaussian_tail")]
550 pub fn gaussian_tail(&mut self, a: f64, sigma: f64) -> f64 {
551 unsafe { sys::gsl_ran_gaussian_tail(self.unwrap_unique(), a, sigma) }
552 }
553
554 /// This function computes results for the tail of a unit Gaussian distribution. They are equivalent to the functions above with a standard deviation of one, sigma = 1.
555 #[doc(alias = "gsl_ran_ugaussian_tail")]
556 pub fn ugaussian_tail(&mut self, a: f64) -> f64 {
557 unsafe { sys::gsl_ran_ugaussian_tail(self.unwrap_unique(), a) }
558 }
559
560 /// This function returns a random integer from the geometric distribution, the number of independent trials with probability p until the first success.
561 /// The probability distribution for geometric variates is,
562 ///
563 /// p(k) = p (1-p)^(k-1)
564 ///
565 /// for k >= 1. Note that the distribution begins with k=1 with this definition. There is another convention in which the exponent k-1 is replaced by k.
566 #[doc(alias = "gsl_ran_geometric")]
567 pub fn geometric(&mut self, p: f64) -> u32 {
568 unsafe { sys::gsl_ran_geometric(self.unwrap_unique(), p) }
569 }
570
571 /// This function returns a random variate from the Type-1 Gumbel distribution. The Type-1 Gumbel distribution function is,
572 ///
573 /// p(x) dx = a b \exp(-(b \exp(-ax) + ax)) dx
574 ///
575 /// for -\infty < x < \infty.
576 #[doc(alias = "gsl_ran_gumbel1")]
577 pub fn gumbel1(&mut self, a: f64, b: f64) -> f64 {
578 unsafe { sys::gsl_ran_gumbel1(self.unwrap_unique(), a, b) }
579 }
580
581 /// This function returns a random variate from the Type-2 Gumbel distribution. The Type-2 Gumbel distribution function is,
582 ///
583 /// p(x) dx = a b x^{-a-1} \exp(-b x^{-a}) dx
584 ///
585 /// for 0 < x < \infty.
586 #[doc(alias = "gsl_ran_gumbel2")]
587 pub fn gumbel2(&mut self, a: f64, b: f64) -> f64 {
588 unsafe { sys::gsl_ran_gumbel2(self.unwrap_unique(), a, b) }
589 }
590
591 /// This function returns a random integer from the hypergeometric distribution. The probability distribution for hypergeometric random variates is,
592 ///
593 /// p(k) = C(n_1, k) C(n_2, t - k) / C(n_1 + n_2, t)
594 ///
595 /// where C(a,b) = a!/(b!(a-b)!) and t <= n_1 + n_2. The domain of k is max(0,t-n_2), ..., min(t,n_1).
596 ///
597 /// If a population contains n_1 elements of “type 1” and n_2 elements of “type 2” then the hypergeometric distribution gives the probability of obtaining
598 /// k elements of “type 1” in t samples from the population without replacement.
599 #[doc(alias = "gsl_ran_hypergeometric")]
600 pub fn hypergeometric(&mut self, n1: u32, n2: u32, t: u32) -> u32 {
601 unsafe { sys::gsl_ran_hypergeometric(self.unwrap_unique(), n1, n2, t) }
602 }
603
604 /// This function returns a random variate from the Landau distribution. The probability distribution for Landau random variates is defined analytically by the complex integral,
605 ///
606 /// p(x) = (1/(2 \pi i)) \int_{c-i\infty}^{c+i\infty} ds exp(s log(s) + x s)
607 ///
608 /// For numerical purposes it is more convenient to use the following equivalent form of the integral,
609 ///
610 /// p(x) = (1/\pi) \int_0^\infty dt \exp(-t \log(t) - x t) \sin(\pi t).
611 #[doc(alias = "gsl_ran_landau")]
612 pub fn landau(&mut self) -> f64 {
613 unsafe { sys::gsl_ran_landau(self.unwrap_unique()) }
614 }
615
616 /// This function returns a random variate from the Laplace distribution with width a. The distribution is,
617 ///
618 /// p(x) dx = {1 \over 2 a} \exp(-|x/a|) dx
619 ///
620 /// for -\infty < x < \infty.
621 #[doc(alias = "gsl_ran_laplace")]
622 pub fn laplace(&mut self, a: f64) -> f64 {
623 unsafe { sys::gsl_ran_laplace(self.unwrap_unique(), a) }
624 }
625
626 /// This function returns a random variate from the Levy symmetric stable distribution with scale c and exponent alpha. The symmetric stable probability distribution is defined by a Fourier transform,
627 ///
628 /// p(x) = {1 \over 2 \pi} \int_{-\infty}^{+\infty} dt \exp(-it x - |c t|^alpha)
629 ///
630 /// There is no explicit solution for the form of p(x) and the library does not define a corresponding pdf function. For \alpha = 1 the distribution reduces to the Cauchy distribution. For \alpha = 2 it is a Gaussian distribution with \sigma = \sqrt{2} c. For \alpha < 1 the tails of the distribution become extremely wide.
631 ///
632 /// The algorithm only works for 0 < alpha <= 2.
633 #[doc(alias = "gsl_ran_levy")]
634 pub fn levy(&mut self, c: f64, alpha: f64) -> f64 {
635 unsafe { sys::gsl_ran_levy(self.unwrap_unique(), c, alpha) }
636 }
637
638 /// This function returns a random variate from the Levy skew stable distribution with scale c, exponent alpha and skewness parameter beta.
639 /// The skewness parameter must lie in the range [-1,1]. The Levy skew stable probability distribution is defined by a Fourier transform,
640 ///
641 /// p(x) = {1 \over 2 \pi} \int_{-\infty}^{+\infty} dt \exp(-it x - |c t|^alpha (1-i beta sign(t) tan(pi alpha/2)))
642 ///
643 /// When \alpha = 1 the term \tan(\pi \alpha/2) is replaced by -(2/\pi)\log|t|. There is no explicit solution for the form of p(x) and the library does not define a corresponding pdf function.
644 /// For \alpha = 2 the distribution reduces to a Gaussian distribution with \sigma = \sqrt{2} c and the skewness parameter has no effect. For \alpha < 1 the tails of the distribution become extremely wide.
645 /// The symmetric distribution corresponds to \beta = 0.
646 ///
647 /// The algorithm only works for 0 < alpha <= 2.
648 ///
649 /// The Levy alpha-stable distributions have the property that if N alpha-stable variates are drawn from the distribution p(c, \alpha, \beta) then the sum Y = X_1 + X_2 + \dots + X_N will also be distributed as an alpha-stable variate, p(N^(1/\alpha) c, \alpha, \beta).
650 #[doc(alias = "gsl_ran_levy_skew")]
651 pub fn levy_skew(&mut self, c: f64, alpha: f64, beta: f64) -> f64 {
652 unsafe { sys::gsl_ran_levy_skew(self.unwrap_unique(), c, alpha, beta) }
653 }
654
655 /// This function returns a random integer from the logarithmic distribution. The probability distribution for logarithmic random variates is,
656 ///
657 /// p(k) = {-1 \over \log(1-p)} {(p^k \over k)}
658 ///
659 /// for k >= 1.
660 #[doc(alias = "gsl_ran_logarithmic")]
661 pub fn logarithmic(&mut self, p: f64) -> u32 {
662 unsafe { sys::gsl_ran_logarithmic(self.unwrap_unique(), p) }
663 }
664
665 /// This function returns a random variate from the logistic distribution. The distribution function is,
666 ///
667 /// p(x) dx = { \exp(-x/a) \over a (1 + \exp(-x/a))^2 } dx
668 ///
669 /// for -\infty < x < +\infty.
670 #[doc(alias = "gsl_ran_logistic")]
671 pub fn logistic(&mut self, a: f64) -> f64 {
672 unsafe { sys::gsl_ran_logistic(self.unwrap_unique(), a) }
673 }
674
675 /// This function returns a random variate from the lognormal distribution. The distribution function is,
676 ///
677 /// p(x) dx = {1 \over x \sqrt{2 \pi \sigma^2} } \exp(-(\ln(x) - \zeta)^2/2 \sigma^2) dx
678 ///
679 /// for x > 0.
680 #[doc(alias = "gsl_ran_lognormal")]
681 pub fn lognormal(&mut self, zeta: f64, sigma: f64) -> f64 {
682 unsafe { sys::gsl_ran_lognormal(self.unwrap_unique(), zeta, sigma) }
683 }
684
685 /// This function returns a random integer from the negative binomial distribution, the number of failures occurring before n successes in independent trials with
686 /// probability p of success. The probability distribution for negative binomial variates is,
687 ///
688 /// p(k) = {\Gamma(n + k) \over \Gamma(k+1) \Gamma(n) } p^n (1-p)^k
689 ///
690 /// Note that n is not required to be an integer.
691 #[doc(alias = "gsl_ran_negative_binomial")]
692 pub fn negative_binomial(&mut self, p: f64, n: f64) -> u32 {
693 unsafe { sys::gsl_ran_negative_binomial(self.unwrap_unique(), p, n) }
694 }
695
696 /// This function returns a random variate from the Pareto distribution of order a. The distribution function is,
697 ///
698 /// p(x) dx = (a/b) / (x/b)^{a+1} dx
699 ///
700 /// for x >= b.
701 #[doc(alias = "gsl_ran_pareto")]
702 pub fn pareto(&mut self, a: f64, b: f64) -> f64 {
703 unsafe { sys::gsl_ran_pareto(self.unwrap_unique(), a, b) }
704 }
705
706 /// This function returns a random integer from the Pascal distribution. The Pascal distribution is simply a negative binomial distribution with an integer value of n.
707 ///
708 /// p(k) = {(n + k - 1)! \over k! (n - 1)! } p^n (1-p)^k
709 ///
710 /// for k >= 0
711 #[doc(alias = "gsl_ran_pascal")]
712 pub fn pascal(&mut self, p: f64, n: u32) -> u32 {
713 unsafe { sys::gsl_ran_pascal(self.unwrap_unique(), p, n) }
714 }
715
716 /// This function returns a random integer from the Poisson distribution with mean mu. The probability distribution for Poisson variates is,
717 ///
718 /// p(k) = {\mu^k \over k!} \exp(-\mu)
719 ///
720 /// for k >= 0.
721 #[doc(alias = "gsl_ran_poisson")]
722 pub fn poisson(&mut self, mu: f64) -> u32 {
723 unsafe { sys::gsl_ran_poisson(self.unwrap_unique(), mu) }
724 }
725
726 /// This function returns a random variate from the Rayleigh distribution with scale parameter sigma. The distribution is,
727 ///
728 /// p(x) dx = {x \over \sigma^2} \exp(- x^2/(2 \sigma^2)) dx
729 ///
730 /// for x > 0.
731 #[doc(alias = "gsl_ran_rayleigh")]
732 pub fn rayleigh(&mut self, sigma: f64) -> f64 {
733 unsafe { sys::gsl_ran_rayleigh(self.unwrap_unique(), sigma) }
734 }
735
736 /// This function returns a random variate from the tail of the Rayleigh distribution with scale parameter sigma and a lower limit of a. The distribution is,
737 ///
738 /// p(x) dx = {x \over \sigma^2} \exp ((a^2 - x^2) /(2 \sigma^2)) dx
739 ///
740 /// for x > a.
741 #[doc(alias = "gsl_ran_rayleigh_tail")]
742 pub fn rayleigh_tail(&mut self, a: f64, sigma: f64) -> f64 {
743 unsafe { sys::gsl_ran_rayleigh_tail(self.unwrap_unique(), a, sigma) }
744 }
745
746 /// This function returns a random direction vector v = (x,y) in two dimensions. The vector is normalized such that |v|^2 = x^2 + y^2 = 1.
747 /// The obvious way to do this is to take a uniform random number between 0 and 2\pi and let x and y be the sine and cosine respectively.
748 /// Two trig functions would have been expensive in the old days, but with modern hardware implementations, this is sometimes the fastest way to go.
749 /// This is the case for the Pentium (but not the case for the Sun Sparcstation).
750 /// One can avoid the trig evaluations by choosing x and y in the interior of a unit circle (choose them at random from the interior of the enclosing square,
751 /// and then reject those that are outside the unit circle), and then dividing by \sqrt{x^2 + y^2}. A much cleverer approach, attributed to von Neumann
752 /// (See Knuth, v2, 3rd ed, p140, exercise 23), requires neither trig nor a square root. In this approach, u and v are chosen at random from the interior of
753 /// a unit circle, and then x=(u^2-v^2)/(u^2+v^2) and y=2uv/(u^2+v^2).
754 ///
755 /// Returns `(x, y)`.
756 #[doc(alias = "gsl_ran_dir_2d")]
757 pub fn dir_2d(&mut self) -> (f64, f64) {
758 let mut x = 0.;
759 let mut y = 0.;
760 unsafe { sys::gsl_ran_dir_2d(self.unwrap_unique(), &mut x, &mut y) };
761 (x, y)
762 }
763
764 /// This function returns a random direction vector v = (x,y) in two dimensions. The vector is normalized such that |v|^2 = x^2 + y^2 = 1.
765 /// The obvious way to do this is to take a uniform random number between 0 and 2\pi and let x and y be the sine and cosine respectively.
766 /// Two trig functions would have been expensive in the old days, but with modern hardware implementations, this is sometimes the fastest way to go.
767 /// This is the case for the Pentium (but not the case for the Sun Sparcstation).
768 /// One can avoid the trig evaluations by choosing x and y in the interior of a unit circle (choose them at random from the interior of the enclosing square,
769 /// and then reject those that are outside the unit circle), and then dividing by \sqrt{x^2 + y^2}. A much cleverer approach, attributed to von Neumann
770 /// (See Knuth, v2, 3rd ed, p140, exercise 23), requires neither trig nor a square root. In this approach, u and v are chosen at random from the interior of
771 /// a unit circle, and then x=(u^2-v^2)/(u^2+v^2) and y=2uv/(u^2+v^2).
772 ///
773 /// Returns `(x, y)`.
774 #[doc(alias = "gsl_ran_dir_2d_trig_method")]
775 pub fn dir_2d_trig_method(&mut self) -> (f64, f64) {
776 let mut x = 0.;
777 let mut y = 0.;
778 unsafe { sys::gsl_ran_dir_2d_trig_method(self.unwrap_unique(), &mut x, &mut y) };
779 (x, y)
780 }
781
782 /// This function returns a random direction vector v = (x,y,z) in three dimensions. The vector is normalized such that |v|^2 = x^2 + y^2 + z^2 = 1.
783 /// The method employed is due to Robert E. Knop (CACM 13, 326 (1970)), and explained in Knuth, v2, 3rd ed, p136. It uses the surprising fact that the
784 /// distribution projected along any axis is actually uniform (this is only true for 3 dimensions).
785 ///
786 /// Returns `(x, y, z)`.
787 #[doc(alias = "gsl_ran_dir_3d")]
788 pub fn dir_3d(&mut self) -> (f64, f64, f64) {
789 let mut x = 0.;
790 let mut y = 0.;
791 let mut z = 0.;
792 unsafe { sys::gsl_ran_dir_3d(self.unwrap_unique(), &mut x, &mut y, &mut z) };
793 (x, y, z)
794 }
795
796 /// This function returns a random direction vector v = (x_1,x_2,...,x_n) in n dimensions. The vector is normalized such that |v|^2 = x_1^2 + x_2^2 + ... + x_n^2 = 1.
797 /// The method uses the fact that a multivariate Gaussian distribution is spherically symmetric. Each component is generated to have a Gaussian distribution, and then
798 /// the components are normalized. The method is described by Knuth, v2, 3rd ed, p135–136, and attributed to G. W. Brown, Modern Mathematics for the Engineer (1956).
799 #[doc(alias = "gsl_ran_dir_nd")]
800 pub fn dir_nd(&mut self, x: &mut [f64]) {
801 unsafe { sys::gsl_ran_dir_nd(self.unwrap_unique(), x.len() as _, x.as_mut_ptr()) }
802 }
803
804 /// This function returns a random variate from the t-distribution. The distribution function is,
805 ///
806 /// p(x) dx = {Gamma((\nu + 1)/2) \over \sqrt{\pi \nu} Gamma(\nu/2)}
807 ///
808 /// (1 + x^2/\nu)^{-(\nu + 1)/2} dx
809 ///
810 /// for -\infty < x < +\infty.
811 #[doc(alias = "gsl_ran_tdist")]
812 pub fn tdist(&mut self, nu: f64) -> f64 {
813 unsafe { sys::gsl_ran_tdist(self.unwrap_unique(), nu) }
814 }
815
816 /// This function returns a random variate from the Weibull distribution. The distribution function is,
817 ///
818 /// p(x) dx = {b \over a^b} x^{b-1} \exp(-(x/a)^b) dx
819 ///
820 /// for x >= 0.
821 #[doc(alias = "gsl_ran_weibull")]
822 pub fn weibull(&mut self, a: f64, b: f64) -> f64 {
823 unsafe { sys::gsl_ran_weibull(self.unwrap_unique(), a, b) }
824 }
825}
826
827impl Clone for Rng {
828 /// This function returns a pointer to a newly created generator which is an exact copy of the generator r.
829 #[doc(alias = "gsl_rng_clone")]
830 fn clone(&self) -> Rng {
831 unsafe { FFI::wrap(sys::gsl_rng_clone(self.unwrap_shared())) }
832 }
833}
834
835ffi_wrapper!(RngType, *const sys::gsl_rng_type);
836
837impl RngType {
838 /// wrapper for name element
839 pub fn name(&self) -> String {
840 let ptr = self.unwrap_shared();
841 if ptr.is_null() {
842 String::new()
843 } else {
844 unsafe {
845 String::from_utf8_lossy(::std::ffi::CStr::from_ptr((*ptr).name).to_bytes())
846 .to_string()
847 }
848 }
849 }
850
851 #[doc(alias = "gsl_rng_default")]
852 pub fn default() -> Self {
853 ffi_wrap!(gsl_rng_default)
854 }
855
856 /// wrapper for max element
857 pub fn max(&self) -> usize {
858 let ptr = self.unwrap_shared();
859 if ptr.is_null() {
860 0
861 } else {
862 unsafe { (*ptr).max as _ }
863 }
864 }
865
866 /// wrapper for min element
867 pub fn min(&self) -> usize {
868 let ptr = self.unwrap_shared();
869 if ptr.is_null() {
870 0
871 } else {
872 unsafe { (*ptr).min as _ }
873 }
874 }
875
876 /// wrapper for size element
877 pub fn size(&self) -> usize {
878 let ptr = self.unwrap_shared();
879 if ptr.is_null() {
880 0
881 } else {
882 unsafe { (*ptr).size }
883 }
884 }
885
886 /// This function returns a pointer to an array of all the available generator types, terminated by a null pointer.
887 /// The function should be called once at the start of the program, if needed. The following code fragment shows how to iterate over the array of generator types to print the names of the available algorithms,
888 ///
889 /// ```Rust
890 /// let t = RngType::types_setup ();
891 ///
892 /// println!("Available generators:");
893 /// for tmp in t.iter() {
894 /// println!("{}", tmp.name);
895 /// }
896 /// ```
897 #[doc(alias = "gsl_rng_types_setup")]
898 pub fn types_setup() -> Vec<RngType> {
899 let ptr = unsafe { sys::gsl_rng_types_setup() };
900 let mut ret = Vec::new();
901
902 if !ptr.is_null() {
903 unsafe {
904 let mut it = 0;
905 loop {
906 let tmp = ptr.offset(it);
907
908 if (*tmp).is_null() {
909 break;
910 }
911 ret.push(RngType::wrap(*tmp as *mut sys::gsl_rng_type));
912 it += 1;
913 }
914 }
915 }
916 ret
917 }
918
919 /// This function reads the environment variables GSL_RNG_TYPE and GSL_RNG_SEED and uses their values to set the corresponding library variables gsl_rng_default and gsl_rng_default_seed. These global variables are defined as follows,
920 ///
921 /// ```C
922 /// extern const gsl_rng_type *gsl_rng_default
923 /// extern unsigned long int gsl_rng_default_seed
924 /// ```
925 ///
926 /// The environment variable GSL_RNG_TYPE should be the name of a generator, such as taus or mt19937. The environment variable GSL_RNG_SEED should contain the desired seed value.
927 /// It is converted to an unsigned long int using the C library function strtoul.
928 ///
929 /// If you don’t specify a generator for GSL_RNG_TYPE then gsl_rng_mt19937 is used as the default. The initial value of gsl_rng_default_seed is zero.
930 /// See rng example in examples folder for more details.
931 #[doc(alias = "gsl_rng_env_setup")]
932 pub fn env_setup() -> Option<RngType> {
933 let tmp = unsafe { sys::gsl_rng_env_setup() };
934
935 if tmp.is_null() {
936 None
937 } else {
938 Some(RngType::wrap(tmp as *mut sys::gsl_rng_type))
939 }
940 }
941}
942
943/// The functions described above make no reference to the actual algorithm used. This is deliberate so that you can switch algorithms without having
944/// to change any of your application source code. The library provides a large number of generators of different types, including simulation quality
945/// generators, generators provided for compatibility with other libraries and historical generators from the past.
946///
947/// The following generators are recommended for use in simulation. They have extremely long periods, low correlation and pass most statistical tests.
948/// For the most reliable source of uncorrelated numbers, the second-generation RANLUX generators have the strongest proof of randomness.
949pub mod algorithms {
950 use types::RngType;
951
952 /// The MT19937 generator of Makoto Matsumoto and Takuji Nishimura is a variant of the twisted generalized feedback shift-register algorithm, and
953 /// is known as the “Mersenne Twister” generator. It has a Mersenne prime period of 2^19937 - 1 (about 10^6000) and is equi-distributed in 623 dimensions.
954 /// It has passed the DIEHARD statistical tests. It uses 624 words of state per generator and is comparable in speed to the other generators. The original
955 /// generator used a default seed of 4357 and choosing s equal to zero in gsl_rng_set reproduces this. Later versions switched to 5489 as the default seed,
956 /// you can choose this explicitly via gsl_rng_set instead if you require it.
957 ///
958 /// For more information see,
959 ///
960 /// Makoto Matsumoto and Takuji Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator”. ACM Transactions
961 /// on Modeling and Computer Simulation, Vol. 8, No. 1 (Jan. 1998), Pages 3–30
962 ///
963 /// The generator gsl_rng_mt19937 uses the second revision of the seeding procedure published by the two authors above in 2002. The original seeding
964 /// procedures could cause spurious artifacts for some seed values. They are still available through the alternative generators gsl_rng_mt19937_1999 and
965 /// gsl_rng_mt19937_1998.
966 #[doc(alias = "gsl_rng_mt19937")]
967 pub fn mt19937() -> RngType {
968 ffi_wrap!(gsl_rng_mt19937)
969 }
970
971 /// The generator ranlxs0 is a second-generation version of the RANLUX algorithm of Lüscher, which produces “luxury random numbers”. This generator
972 /// provides single precision output (24 bits) at three luxury levels ranlxs0, ranlxs1 and ranlxs2, in increasing order of strength. It uses double-precision
973 /// floating point arithmetic internally and can be significantly faster than the integer version of ranlux, particularly on 64-bit architectures. The period
974 /// of the generator is about 10^171. The algorithm has mathematically proven properties and can provide truly decorrelated numbers at a known level of
975 /// randomness. The higher luxury levels provide increased decorrelation between samples as an additional safety margin.
976 ///
977 /// Note that the range of allowed seeds for this generator is [0,2^31-1]. Higher seed values are wrapped modulo 2^31.
978 #[doc(alias = "gsl_rng_ranlxs0")]
979 pub fn ranlxs0() -> RngType {
980 ffi_wrap!(gsl_rng_ranlxs0)
981 }
982
983 /// The generator ranlxs0 is a second-generation version of the RANLUX algorithm of Lüscher, which produces “luxury random numbers”. This generator
984 /// provides single precision output (24 bits) at three luxury levels ranlxs0, ranlxs1 and ranlxs2, in increasing order of strength. It uses double-precision
985 /// floating point arithmetic internally and can be significantly faster than the integer version of ranlux, particularly on 64-bit architectures. The period
986 /// of the generator is about 10^171. The algorithm has mathematically proven properties and can provide truly decorrelated numbers at a known level of
987 /// randomness. The higher luxury levels provide increased decorrelation between samples as an additional safety margin.
988 ///
989 /// Note that the range of allowed seeds for this generator is [0,2^31-1]. Higher seed values are wrapped modulo 2^31.
990 #[doc(alias = "gsl_rng_ranlxs1")]
991 pub fn ranlxs1() -> RngType {
992 ffi_wrap!(gsl_rng_ranlxs1)
993 }
994
995 /// The generator ranlxs0 is a second-generation version of the RANLUX algorithm of Lüscher, which produces “luxury random numbers”. This generator
996 /// provides single precision output (24 bits) at three luxury levels ranlxs0, ranlxs1 and ranlxs2, in increasing order of strength. It uses double-precision
997 /// floating point arithmetic internally and can be significantly faster than the integer version of ranlux, particularly on 64-bit architectures. The period
998 /// of the generator is about 10^171. The algorithm has mathematically proven properties and can provide truly decorrelated numbers at a known level of
999 /// randomness. The higher luxury levels provide increased decorrelation between samples as an additional safety margin.
1000 ///
1001 /// Note that the range of allowed seeds for this generator is [0,2^31-1]. Higher seed values are wrapped modulo 2^31.
1002 #[doc(alias = "gsl_rng_ranlxs2")]
1003 pub fn ranlxs2() -> RngType {
1004 ffi_wrap!(gsl_rng_ranlxs2)
1005 }
1006
1007 /// This generator produces double precision output (48 bits) from the RANLXS generator. The library provides two luxury levels ranlxd1 and ranlxd2,
1008 /// in increasing order of strength.
1009 #[doc(alias = "gsl_rng_ranlxd1")]
1010 pub fn ranlxd1() -> RngType {
1011 ffi_wrap!(gsl_rng_ranlxd1)
1012 }
1013
1014 /// This generator produces double precision output (48 bits) from the RANLXS generator. The library provides two luxury levels ranlxd1 and ranlxd2,
1015 /// in increasing order of strength.
1016 #[doc(alias = "gsl_rng_ranlxd2")]
1017 pub fn ranlxd2() -> RngType {
1018 ffi_wrap!(gsl_rng_ranlxd2)
1019 }
1020
1021 /// The ranlux generator is an implementation of the original algorithm developed by Lüscher. It uses a lagged-fibonacci-with-skipping algorithm to
1022 /// produce “luxury random numbers”. It is a 24-bit generator, originally designed for single-precision IEEE floating point numbers. This
1023 /// implementation is based on integer arithmetic, while the second-generation versions RANLXS and RANLXD described above provide floating-point
1024 /// implementations which will be faster on many platforms. The period of the generator is about 10^171. The algorithm has mathematically proven
1025 /// properties and it can provide truly decorrelated numbers at a known level of randomness. The default level of decorrelation recommended by
1026 /// Lüscher is provided by gsl_rng_ranlux, while gsl_rng_ranlux389 gives the highest level of randomness, with all 24 bits decorrelated. Both
1027 /// types of generator use 24 words of state per generator.
1028 ///
1029 /// For more information see,
1030 ///
1031 /// M. Lüscher, “A portable high-quality random number generator for lattice field theory calculations”, Computer Physics Communications, 79 (1994) 100–110.
1032 /// F. James, “RANLUX: A Fortran implementation of the high-quality pseudo-random number generator of Lüscher”, Computer Physics Communications, 79 (1994) 111–114
1033 #[doc(alias = "gsl_rng_ranlux")]
1034 pub fn ranlux() -> RngType {
1035 ffi_wrap!(gsl_rng_ranlux)
1036 }
1037
1038 /// The ranlux generator is an implementation of the original algorithm developed by Lüscher. It uses a lagged-fibonacci-with-skipping algorithm to
1039 /// produce “luxury random numbers”. It is a 24-bit generator, originally designed for single-precision IEEE floating point numbers. This
1040 /// implementation is based on integer arithmetic, while the second-generation versions RANLXS and RANLXD described above provide floating-point
1041 /// implementations which will be faster on many platforms. The period of the generator is about 10^171. The algorithm has mathematically proven
1042 /// properties and it can provide truly decorrelated numbers at a known level of randomness. The default level of decorrelation recommended by
1043 /// Lüscher is provided by gsl_rng_ranlux, while gsl_rng_ranlux389 gives the highest level of randomness, with all 24 bits decorrelated. Both
1044 /// types of generator use 24 words of state per generator.
1045 ///
1046 /// For more information see,
1047 ///
1048 /// M. Lüscher, “A portable high-quality random number generator for lattice field theory calculations”, Computer Physics Communications, 79 (1994) 100–110.
1049 /// F. James, “RANLUX: A Fortran implementation of the high-quality pseudo-random number generator of Lüscher”, Computer Physics Communications, 79 (1994) 111–114
1050 #[doc(alias = "gsl_rng_ranlux389")]
1051 pub fn ranlux389() -> RngType {
1052 ffi_wrap!(gsl_rng_ranlux389)
1053 }
1054
1055 /// This is a combined multiple recursive generator by L’Ecuyer. Its sequence is,
1056 ///
1057 /// z_n = (x_n - y_n) mod m_1
1058 ///
1059 /// where the two underlying generators x_n and y_n are,
1060 ///
1061 /// x_n = (a_1 x_{n-1} + a_2 x_{n-2} + a_3 x_{n-3}) mod m_1
1062 /// y_n = (b_1 y_{n-1} + b_2 y_{n-2} + b_3 y_{n-3}) mod m_2
1063 ///
1064 /// with coefficients a_1 = 0, a_2 = 63308, a_3 = -183326, b_1 = 86098, b_2 = 0, b_3 = -539608, and moduli m_1 = 2^31 - 1 = 2147483647 and m_2 = 2145483479.
1065 ///
1066 /// The period of this generator is lcm(m_1^3-1, m_2^3-1), which is approximately 2^185 (about 10^56). It uses 6 words of state per generator. For more information see,
1067 ///
1068 /// P. L’Ecuyer, “Combined Multiple Recursive Random Number Generators”, Operations Research, 44, 5 (1996), 816–822.
1069 #[doc(alias = "gsl_rng_cmrg")]
1070 pub fn cmrg() -> RngType {
1071 ffi_wrap!(gsl_rng_cmrg)
1072 }
1073
1074 /// This is a fifth-order multiple recursive generator by L’Ecuyer, Blouin and Coutre. Its sequence is,
1075 ///
1076 /// x_n = (a_1 x_{n-1} + a_5 x_{n-5}) mod m
1077 ///
1078 /// with a_1 = 107374182, a_2 = a_3 = a_4 = 0, a_5 = 104480 and m = 2^31 - 1.
1079 ///
1080 /// The period of this generator is about 10^46. It uses 5 words of state per generator. More information can be found in the following paper,
1081 ///
1082 /// P. L’Ecuyer, F. Blouin, and R. Coutre, “A search for good multiple recursive random number generators”, ACM Transactions on Modeling and Computer Simulation 3, 87–98 (1993).
1083 #[doc(alias = "gsl_rng_mrg")]
1084 pub fn mrg() -> RngType {
1085 ffi_wrap!(gsl_rng_mrg)
1086 }
1087
1088 /// This is a maximally equidistributed combined Tausworthe generator by L’Ecuyer. The sequence is,
1089 ///
1090 /// x_n = (s1_n ^^ s2_n ^^ s3_n)
1091 ///
1092 /// where,
1093 ///
1094 /// s1_{n+1} = (((s1_n&4294967294)<<12)^^(((s1_n<<13)^^s1_n)>>19))
1095 /// s2_{n+1} = (((s2_n&4294967288)<< 4)^^(((s2_n<< 2)^^s2_n)>>25))
1096 /// s3_{n+1} = (((s3_n&4294967280)<<17)^^(((s3_n<< 3)^^s3_n)>>11))
1097 ///
1098 /// computed modulo 2^32. In the formulas above ^^ denotes “exclusive-or”. Note that the algorithm relies on the properties of 32-bit
1099 /// unsigned integers and has been implemented using a bitmask of 0xFFFFFFFF to make it work on 64 bit machines.
1100 ///
1101 /// The period of this generator is 2^88 (about 10^26). It uses 3 words of state per generator. For more information see,
1102 ///
1103 /// P. L’Ecuyer, “Maximally Equidistributed Combined Tausworthe Generators”, Mathematics of Computation, 65, 213 (1996), 203–213.
1104 ///
1105 /// The generator gsl_rng_taus2 uses the same algorithm as gsl_rng_taus but with an improved seeding procedure described in the paper,
1106 ///
1107 /// P. L’Ecuyer, “Tables of Maximally Equidistributed Combined LFSR Generators”, Mathematics of Computation, 68, 225 (1999), 261–269
1108 ///
1109 /// The generator gsl_rng_taus2 should now be used in preference to gsl_rng_taus.
1110 #[doc(alias = "gsl_rng_taus")]
1111 pub fn taus() -> RngType {
1112 ffi_wrap!(gsl_rng_taus)
1113 }
1114
1115 /// This is a maximally equidistributed combined Tausworthe generator by L’Ecuyer. The sequence is,
1116 ///
1117 /// x_n = (s1_n ^^ s2_n ^^ s3_n)
1118 ///
1119 /// where,
1120 ///
1121 /// s1_{n+1} = (((s1_n&4294967294)<<12)^^(((s1_n<<13)^^s1_n)>>19))
1122 /// s2_{n+1} = (((s2_n&4294967288)<< 4)^^(((s2_n<< 2)^^s2_n)>>25))
1123 /// s3_{n+1} = (((s3_n&4294967280)<<17)^^(((s3_n<< 3)^^s3_n)>>11))
1124 ///
1125 /// computed modulo 2^32. In the formulas above ^^ denotes “exclusive-or”. Note that the algorithm relies on the properties of 32-bit
1126 /// unsigned integers and has been implemented using a bitmask of 0xFFFFFFFF to make it work on 64 bit machines.
1127 ///
1128 /// The period of this generator is 2^88 (about 10^26). It uses 3 words of state per generator. For more information see,
1129 ///
1130 /// P. L’Ecuyer, “Maximally Equidistributed Combined Tausworthe Generators”, Mathematics of Computation, 65, 213 (1996), 203–213.
1131 ///
1132 /// The generator gsl_rng_taus2 uses the same algorithm as gsl_rng_taus but with an improved seeding procedure described in the paper,
1133 ///
1134 /// P. L’Ecuyer, “Tables of Maximally Equidistributed Combined LFSR Generators”, Mathematics of Computation, 68, 225 (1999), 261–269
1135 ///
1136 /// The generator gsl_rng_taus2 should now be used in preference to gsl_rng_taus.
1137 #[doc(alias = "gsl_rng_taus2")]
1138 pub fn taus2() -> RngType {
1139 ffi_wrap!(gsl_rng_taus2)
1140 }
1141
1142 /// The gfsr4 generator is like a lagged-fibonacci generator, and produces each number as an xor’d sum of four previous values.
1143 ///
1144 /// r_n = r_{n-A} ^^ r_{n-B} ^^ r_{n-C} ^^ r_{n-D}
1145 ///
1146 /// Ziff (ref below) notes that “it is now widely known” that two-tap registers (such as R250, which is described below) have serious
1147 /// flaws, the most obvious one being the three-point correlation that comes from the definition of the generator. Nice mathematical
1148 /// properties can be derived for GFSR’s, and numerics bears out the claim that 4-tap GFSR’s with appropriately chosen offsets are as
1149 /// random as can be measured, using the author’s test.
1150 ///
1151 /// This implementation uses the values suggested the example on p392 of Ziff’s article: A=471, B=1586, C=6988, D=9689.
1152 ///
1153 /// If the offsets are appropriately chosen (such as the one ones in this implementation), then the sequence is said to be maximal;
1154 /// that means that the period is 2^D - 1, where D is the longest lag. (It is one less than 2^D because it is not permitted to have all
1155 /// zeros in the ra[] array.) For this implementation with D=9689 that works out to about 10^2917.
1156 ///
1157 /// Note that the implementation of this generator using a 32-bit integer amounts to 32 parallel implementations of one-bit generators.
1158 /// One consequence of this is that the period of this 32-bit generator is the same as for the one-bit generator. Moreover, this
1159 /// independence means that all 32-bit patterns are equally likely, and in particular that 0 is an allowed random value. (We are grateful
1160 /// to Heiko Bauke for clarifying for us these properties of GFSR random number generators.)
1161 ///
1162 /// For more information see,
1163 ///
1164 /// Robert M. Ziff, “Four-tap shift-register-sequence random-number generators”, Computers in Physics, 12(4), Jul/Aug 1998, pp 385–392.
1165 #[doc(alias = "gsl_rng_gfsr4")]
1166 pub fn gfsr4() -> RngType {
1167 ffi_wrap!(gsl_rng_gfsr4)
1168 }
1169}
1170
1171/// The standard Unix random number generators rand, random and rand48 are provided as part of GSL. Although these generators are widely
1172/// available individually often they aren’t all available on the same platform. This makes it difficult to write portable code using them
1173/// and so we have included the complete set of Unix generators in GSL for convenience. Note that these generators don’t produce high-quality
1174/// randomness and aren’t suitable for work requiring accurate statistics. However, if you won’t be measuring statistical quantities and just
1175/// want to introduce some variation into your program then these generators are quite acceptable.
1176pub mod unix {
1177 use types::RngType;
1178
1179 /// This is the BSD rand generator. Its sequence is
1180 ///
1181 /// x_{n+1} = (a x_n + c) mod m
1182 ///
1183 /// with a = 1103515245, c = 12345 and m = 2^31. The seed specifies the initial value, x_1. The period of this generator is 2^31, and it
1184 /// uses 1 word of storage per generator.
1185 #[doc(alias = "gsl_rng_rand")]
1186 pub fn rand() -> RngType {
1187 ffi_wrap!(gsl_rng_rand)
1188 }
1189
1190 /// These generators implement the random family of functions, a set of linear feedback shift register generators originally used in BSD
1191 /// Unix. There are several versions of random in use today: the original BSD version (e.g. on SunOS4), a libc5 version (found on older
1192 /// GNU/Linux systems) and a glibc2 version. Each version uses a different seeding procedure, and thus produces different sequences.
1193 ///
1194 /// The original BSD routines accepted a variable length buffer for the generator state, with longer buffers providing higher-quality
1195 /// randomness. The random function implemented algorithms for buffer lengths of 8, 32, 64, 128 and 256 bytes, and the algorithm with the
1196 /// largest length that would fit into the user-supplied buffer was used. To support these algorithms additional generators are available
1197 /// with the following names,
1198 ///
1199 /// * gsl_rng_random8_bsd
1200 /// * gsl_rng_random32_bsd
1201 /// * gsl_rng_random64_bsd
1202 /// * gsl_rng_random128_bsd
1203 /// * gsl_rng_random256_bsd
1204 ///
1205 /// where the numeric suffix indicates the buffer length. The original BSD random function used a 128-byte default buffer and so
1206 /// gsl_rng_random_bsd has been made equivalent to gsl_rng_random128_bsd. Corresponding versions of the libc5 and glibc2 generators are
1207 /// also available, with the names gsl_rng_random8_libc5, gsl_rng_random8_glibc2, etc.
1208 #[doc(alias = "gsl_rng_random_bsd")]
1209 pub fn random_bsd() -> RngType {
1210 ffi_wrap!(gsl_rng_random_bsd)
1211 }
1212
1213 /// These generators implement the random family of functions, a set of linear feedback shift register generators originally used in BSD
1214 /// Unix. There are several versions of random in use today: the original BSD version (e.g. on SunOS4), a libc5 version (found on older
1215 /// GNU/Linux systems) and a glibc2 version. Each version uses a different seeding procedure, and thus produces different sequences.
1216 ///
1217 /// The original BSD routines accepted a variable length buffer for the generator state, with longer buffers providing higher-quality
1218 /// randomness. The random function implemented algorithms for buffer lengths of 8, 32, 64, 128 and 256 bytes, and the algorithm with the
1219 /// largest length that would fit into the user-supplied buffer was used. To support these algorithms additional generators are available
1220 /// with the following names,
1221 ///
1222 /// * gsl_rng_random8_bsd
1223 /// * gsl_rng_random32_bsd
1224 /// * gsl_rng_random64_bsd
1225 /// * gsl_rng_random128_bsd
1226 /// * gsl_rng_random256_bsd
1227 ///
1228 /// where the numeric suffix indicates the buffer length. The original BSD random function used a 128-byte default buffer and so
1229 /// gsl_rng_random_bsd has been made equivalent to gsl_rng_random128_bsd. Corresponding versions of the libc5 and glibc2 generators are
1230 /// also available, with the names gsl_rng_random8_libc5, gsl_rng_random8_glibc2, etc.
1231 #[doc(alias = "gsl_rng_random_libc5")]
1232 pub fn random_libc5() -> RngType {
1233 ffi_wrap!(gsl_rng_random_libc5)
1234 }
1235
1236 /// These generators implement the random family of functions, a set of linear feedback shift register generators originally used in BSD
1237 /// Unix. There are several versions of random in use today: the original BSD version (e.g. on SunOS4), a libc5 version (found on older
1238 /// GNU/Linux systems) and a glibc2 version. Each version uses a different seeding procedure, and thus produces different sequences.
1239 ///
1240 /// The original BSD routines accepted a variable length buffer for the generator state, with longer buffers providing higher-quality
1241 /// randomness. The random function implemented algorithms for buffer lengths of 8, 32, 64, 128 and 256 bytes, and the algorithm with the
1242 /// largest length that would fit into the user-supplied buffer was used. To support these algorithms additional generators are available
1243 /// with the following names,
1244 ///
1245 /// * gsl_rng_random8_bsd
1246 /// * gsl_rng_random32_bsd
1247 /// * gsl_rng_random64_bsd
1248 /// * gsl_rng_random128_bsd
1249 /// * gsl_rng_random256_bsd
1250 ///
1251 /// where the numeric suffix indicates the buffer length. The original BSD random function used a 128-byte default buffer and so
1252 /// gsl_rng_random_bsd has been made equivalent to gsl_rng_random128_bsd. Corresponding versions of the libc5 and glibc2 generators are
1253 /// also available, with the names gsl_rng_random8_libc5, gsl_rng_random8_glibc2, etc.
1254 #[doc(alias = "gsl_rng_random_glibc2")]
1255 pub fn random_glibc2() -> RngType {
1256 ffi_wrap!(gsl_rng_random_glibc2)
1257 }
1258
1259 /// This is the Unix rand48 generator. Its sequence is
1260 ///
1261 /// x_{n+1} = (a x_n + c) mod m
1262 /// defined on 48-bit unsigned integers with a = 25214903917, c = 11 and m = 2^48. The seed specifies the upper 32 bits of the initial
1263 /// value, x_1, with the lower 16 bits set to 0x330E. The function gsl_rng_get returns the upper 32 bits from each term of the sequence.
1264 /// This does not have a direct parallel in the original rand48 functions, but forcing the result to type long int reproduces the output
1265 /// of mrand48. The function gsl_rng_uniform uses the full 48 bits of internal state to return the double precision number x_n/m, which
1266 /// is equivalent to the function drand48. Note that some versions of the GNU C Library contained a bug in mrand48 function which caused
1267 /// it to produce different results (only the lower 16-bits of the return value were set).
1268 #[doc(alias = "gsl_rng_rand48")]
1269 pub fn rand48() -> RngType {
1270 ffi_wrap!(gsl_rng_rand48)
1271 }
1272}
1273
1274/// ## Other random number generators
1275///
1276/// The generators in this section are provided for compatibility with existing libraries. If you are converting an existing program to use GSL then
1277/// you can select these generators to check your new implementation against the original one, using the same random number generator. After verifying
1278/// that your new program reproduces the original results you can then switch to a higher-quality generator.
1279///
1280/// Note that most of the generators in this section are based on single linear congruence relations, which are the least sophisticated type of generator.
1281/// In particular, linear congruences have poor properties when used with a non-prime modulus, as several of these routines do (e.g. with a power of two modulus,
1282/// 2^31 or 2^32). This leads to periodicity in the least significant bits of each number, with only the higher bits having any randomness.
1283/// Thus if you want to produce a random bitstream it is best to avoid using the least significant bits.
1284pub mod other {
1285 use types::RngType;
1286
1287 /// This is the CRAY random number generator RANF. Its sequence is
1288 ///
1289 /// x_{n+1} = (a x_n) mod m
1290 /// defined on 48-bit unsigned integers with a = 44485709377909 and m = 2^48. The seed specifies the lower 32 bits of the initial value, x_1, with the lowest bit set to prevent the seed taking an even value. The upper 16 bits of x_1 are set to 0. A consequence of this procedure is that the pairs of seeds 2 and 3, 4 and 5, etc. produce the same sequences.
1291 ///
1292 /// The generator compatible with the CRAY MATHLIB routine RANF. It produces double precision floating point numbers which should be identical to those from the original RANF.
1293 ///
1294 /// There is a subtlety in the implementation of the seeding. The initial state is reversed through one step, by multiplying by the modular inverse of a mod m. This is done for compatibility with the original CRAY implementation.
1295 ///
1296 /// Note that you can only seed the generator with integers up to 2^32, while the original CRAY implementation uses non-portable wide integers which can cover all 2^48 states of the generator.
1297 ///
1298 /// The function gsl_rng_get returns the upper 32 bits from each term of the sequence. The function gsl_rng_uniform uses the full 48 bits to return the double precision number x_n/m.
1299 ///
1300 /// The period of this generator is 2^46.
1301 #[doc(alias = "gsl_rng_ranf")]
1302 pub fn ranf() -> RngType {
1303 ffi_wrap!(gsl_rng_ranf)
1304 }
1305
1306 /// This is the RANMAR lagged-fibonacci generator of Marsaglia, Zaman and Tsang. It is a 24-bit generator, originally designed for single-precision IEEE floating point numbers.
1307 /// It was included in the CERNLIB high-energy physics library.
1308 #[doc(alias = "gsl_rng_ranmar")]
1309 pub fn ranmar() -> RngType {
1310 ffi_wrap!(gsl_rng_ranmar)
1311 }
1312
1313 /// This is the shift-register generator of Kirkpatrick and Stoll. The sequence is based on the recurrence
1314 ///
1315 /// x_n = x_{n-103} ^^ x_{n-250}
1316 /// where ^^ denotes “exclusive-or”, defined on 32-bit words. The period of this generator is about 2^250 and it uses 250 words of state per generator.
1317 ///
1318 /// For more information see,
1319 ///
1320 /// S. Kirkpatrick and E. Stoll, “A very fast shift-register sequence random number generator”, Journal of Computational Physics, 40, 517–526 (1981)
1321 #[doc(alias = "gsl_rng_r250")]
1322 pub fn r250() -> RngType {
1323 ffi_wrap!(gsl_rng_r250)
1324 }
1325
1326 /// This is an earlier version of the twisted generalized feedback shift-register generator, and has been superseded by the development of MT19937. However, it is
1327 /// still an acceptable generator in its own right. It has a period of 2^800 and uses 33 words of storage per generator.
1328 ///
1329 /// For more information see,
1330 ///
1331 /// Makoto Matsumoto and Yoshiharu Kurita, “Twisted GFSR Generators II”, ACM Transactions on Modelling and Computer Simulation, Vol. 4, No. 3, 1994, pages 254–266.
1332 #[doc(alias = "gsl_rng_tt800")]
1333 pub fn tt800() -> RngType {
1334 ffi_wrap!(gsl_rng_tt800)
1335 }
1336
1337 /// This is the VAX generator MTH$RANDOM. Its sequence is,
1338 ///
1339 /// x_{n+1} = (a x_n + c) mod m
1340 ///
1341 /// with a = 69069, c = 1 and m = 2^32. The seed specifies the initial value, x_1. The period of this generator is 2^32 and it uses 1 word of storage per generator.
1342 #[doc(alias = "gsl_rng_vax")]
1343 pub fn vax() -> RngType {
1344 ffi_wrap!(gsl_rng_vax)
1345 }
1346
1347 /// This is the random number generator from the INMOS Transputer Development system. Its sequence is,
1348 ///
1349 /// x_{n+1} = (a x_n) mod m
1350 ///
1351 /// with a = 1664525 and m = 2^32. The seed specifies the initial value, x_1.
1352 #[doc(alias = "gsl_rng_transputer")]
1353 pub fn transputer() -> RngType {
1354 ffi_wrap!(gsl_rng_transputer)
1355 }
1356
1357 /// This is the IBM RANDU generator. Its sequence is
1358 ///
1359 /// x_{n+1} = (a x_n) mod m
1360 ///
1361 /// with a = 65539 and m = 2^31. The seed specifies the initial value, x_1. The period of this generator was only 2^29. It has become a textbook example of a poor generator.
1362 #[doc(alias = "gsl_rng_randu")]
1363 pub fn randu() -> RngType {
1364 ffi_wrap!(gsl_rng_randu)
1365 }
1366
1367 /// This is Park and Miller’s “minimal standard” MINSTD generator, a simple linear congruence which takes care to avoid the major pitfalls of such algorithms. Its sequence is,
1368 ///
1369 /// x_{n+1} = (a x_n) mod m
1370 ///
1371 /// with a = 16807 and m = 2^31 - 1 = 2147483647. The seed specifies the initial value, x_1. The period of this generator is about 2^31.
1372 ///
1373 /// This generator was used in the IMSL Library (subroutine RNUN) and in MATLAB (the RAND function) in the past. It is also sometimes known by the acronym "GGL" (I'm not sure what that stands for).
1374 ///
1375 /// For more information see,
1376 ///
1377 /// Park and Miller, "Random Number Generators: Good ones are hard to find", Communications of the ACM, October 1988, Volume 31, No 10, pages 1192–1201.
1378 #[doc(alias = "gsl_rng_minstd")]
1379 pub fn minstd() -> RngType {
1380 ffi_wrap!(gsl_rng_minstd)
1381 }
1382
1383 /// This is a reimplementation of the 16-bit SLATEC random number generator RUNIF. A generalization of the generator to 32 bits is provided by gsl_rng_uni32.
1384 /// The original source code is available from NETLIB.
1385 #[doc(alias = "gsl_rng_uni")]
1386 pub fn uni() -> RngType {
1387 ffi_wrap!(gsl_rng_uni)
1388 }
1389
1390 /// This is a reimplementation of the 16-bit SLATEC random number generator RUNIF. A generalization of the generator to 32 bits is provided by gsl_rng_uni32.
1391 /// The original source code is available from NETLIB.
1392 #[doc(alias = "gsl_rng_uni32")]
1393 pub fn uni32() -> RngType {
1394 ffi_wrap!(gsl_rng_uni32)
1395 }
1396
1397 /// This is the SLATEC random number generator RAND. It is ancient. The original source code is available from NETLIB.
1398 #[doc(alias = "gsl_rng_slatec")]
1399 pub fn slatec() -> RngType {
1400 ffi_wrap!(gsl_rng_slatec)
1401 }
1402
1403 /// This is the ZUFALL lagged Fibonacci series generator of Peterson. Its sequence is,
1404 ///
1405 /// t = u_{n-273} + u_{n-607}
1406 /// u_n = t - floor(t)
1407 ///
1408 /// The original source code is available from NETLIB. For more information see,
1409 ///
1410 /// W. Petersen, “Lagged Fibonacci Random Number Generators for the NEC SX-3”, International Journal of High Speed Computing (1994).
1411 #[doc(alias = "gsl_rng_zuf")]
1412 pub fn zuf() -> RngType {
1413 ffi_wrap!(gsl_rng_zuf)
1414 }
1415
1416 /// This is a second-order multiple recursive generator described by Knuth in Seminumerical Algorithms, 3rd Ed., page 108. Its sequence is,
1417 ///
1418 /// x_n = (a_1 x_{n-1} + a_2 x_{n-2}) mod m
1419 ///
1420 /// with a_1 = 271828183, a_2 = 314159269, and m = 2^31 - 1.
1421 #[doc(alias = "gsl_rng_knuthran2")]
1422 pub fn knuthran2() -> RngType {
1423 ffi_wrap!(gsl_rng_knuthran2)
1424 }
1425
1426 /// This is a second-order multiple recursive generator described by Knuth in Seminumerical Algorithms, 3rd Ed., Section 3.6. Knuth provides
1427 /// its C code. The updated routine gsl_rng_knuthran2002 is from the revised 9th printing and corrects some weaknesses in the earlier version,
1428 /// which is implemented as gsl_rng_knuthran.
1429 #[doc(alias = "gsl_rng_knuthran2002")]
1430 pub fn knuthran2002() -> RngType {
1431 ffi_wrap!(gsl_rng_knuthran2002)
1432 }
1433
1434 /// This is a second-order multiple recursive generator described by Knuth in Seminumerical Algorithms, 3rd Ed., Section 3.6. Knuth provides
1435 /// its C code. The updated routine gsl_rng_knuthran2002 is from the revised 9th printing and corrects some weaknesses in the earlier version,
1436 /// which is implemented as gsl_rng_knuthran.
1437 #[doc(alias = "gsl_rng_knuthran")]
1438 pub fn knuthran() -> RngType {
1439 ffi_wrap!(gsl_rng_knuthran)
1440 }
1441
1442 /// This multiplicative generator is taken from Knuth’s Seminumerical Algorithms, 3rd Ed., pages 106–108. Their sequence is,
1443 ///
1444 /// x_{n+1} = (a x_n) mod m
1445 ///
1446 /// where the seed specifies the initial value, x_1. The parameters a and m are as follows, Borosh-Niederreiter: a = 1812433253,
1447 /// m = 2^32, Fishman18: a = 62089911, m = 2^31 - 1, Fishman20: a = 48271, m = 2^31 - 1, L’Ecuyer: a = 40692, m = 2^31 - 249,
1448 /// Waterman: a = 1566083941, m = 2^32.
1449 #[doc(alias = "gsl_rng_borosh13")]
1450 pub fn borosh13() -> RngType {
1451 ffi_wrap!(gsl_rng_borosh13)
1452 }
1453
1454 /// This multiplicative generator is taken from Knuth’s Seminumerical Algorithms, 3rd Ed., pages 106–108. Their sequence is,
1455 ///
1456 /// x_{n+1} = (a x_n) mod m
1457 ///
1458 /// where the seed specifies the initial value, x_1. The parameters a and m are as follows, Borosh-Niederreiter: a = 1812433253,
1459 /// m = 2^32, Fishman18: a = 62089911, m = 2^31 - 1, Fishman20: a = 48271, m = 2^31 - 1, L’Ecuyer: a = 40692, m = 2^31 - 249,
1460 /// Waterman: a = 1566083941, m = 2^32.
1461 #[doc(alias = "gsl_rng_fishman18")]
1462 pub fn fishman18() -> RngType {
1463 ffi_wrap!(gsl_rng_fishman18)
1464 }
1465
1466 /// This multiplicative generator is taken from Knuth’s Seminumerical Algorithms, 3rd Ed., pages 106–108. Their sequence is,
1467 ///
1468 /// x_{n+1} = (a x_n) mod m
1469 ///
1470 /// where the seed specifies the initial value, x_1. The parameters a and m are as follows, Borosh-Niederreiter: a = 1812433253,
1471 /// m = 2^32, Fishman18: a = 62089911, m = 2^31 - 1, Fishman20: a = 48271, m = 2^31 - 1, L’Ecuyer: a = 40692, m = 2^31 - 249,
1472 /// Waterman: a = 1566083941, m = 2^32.
1473 #[doc(alias = "gsl_rng_fishman20")]
1474 pub fn fishman20() -> RngType {
1475 ffi_wrap!(gsl_rng_fishman20)
1476 }
1477
1478 /// This multiplicative generator is taken from Knuth’s Seminumerical Algorithms, 3rd Ed., pages 106–108. Their sequence is,
1479 ///
1480 /// x_{n+1} = (a x_n) mod m
1481 ///
1482 /// where the seed specifies the initial value, x_1. The parameters a and m are as follows, Borosh-Niederreiter: a = 1812433253,
1483 /// m = 2^32, Fishman18: a = 62089911, m = 2^31 - 1, Fishman20: a = 48271, m = 2^31 - 1, L’Ecuyer: a = 40692, m = 2^31 - 249,
1484 /// Waterman: a = 1566083941, m = 2^32.
1485 #[doc(alias = "gsl_rng_lecuyer21")]
1486 pub fn lecuyer21() -> RngType {
1487 ffi_wrap!(gsl_rng_lecuyer21)
1488 }
1489
1490 /// This multiplicative generator is taken from Knuth’s Seminumerical Algorithms, 3rd Ed., pages 106–108. Their sequence is,
1491 ///
1492 /// x_{n+1} = (a x_n) mod m
1493 ///
1494 /// where the seed specifies the initial value, x_1. The parameters a and m are as follows, Borosh-Niederreiter: a = 1812433253,
1495 /// m = 2^32, Fishman18: a = 62089911, m = 2^31 - 1, Fishman20: a = 48271, m = 2^31 - 1, L’Ecuyer: a = 40692, m = 2^31 - 249,
1496 /// Waterman: a = 1566083941, m = 2^32.
1497 #[doc(alias = "gsl_rng_waterman14")]
1498 pub fn waterman14() -> RngType {
1499 ffi_wrap!(gsl_rng_waterman14)
1500 }
1501
1502 /// This is the L’Ecuyer–Fishman random number generator. It is taken from Knuth’s Seminumerical Algorithms, 3rd Ed., page 108. Its sequence is,
1503 ///
1504 /// z_{n+1} = (x_n - y_n) mod m
1505 ///
1506 /// with m = 2^31 - 1. x_n and y_n are given by the fishman20 and lecuyer21 algorithms. The seed specifies the initial value, x_1.
1507 #[doc(alias = "gsl_rng_fishman2x")]
1508 pub fn fishman2x() -> RngType {
1509 ffi_wrap!(gsl_rng_fishman2x)
1510 }
1511
1512 /// This is the Coveyou random number generator. It is taken from Knuth’s Seminumerical Algorithms, 3rd Ed., Section 3.2.2. Its sequence is,
1513 ///
1514 /// x_{n+1} = (x_n (x_n + 1)) mod m
1515 ///
1516 /// with m = 2^32. The seed specifies the initial value, x_1.
1517 #[doc(alias = "gsl_rng_coveyou")]
1518 pub fn coveyou() -> RngType {
1519 ffi_wrap!(gsl_rng_coveyou)
1520 }
1521}