diff --git a/src/libstd/rand/distributions/gamma.rs b/src/libstd/rand/distributions/gamma.rs index dec0d3922d32..ae7ff99af924 100644 --- a/src/libstd/rand/distributions/gamma.rs +++ b/src/libstd/rand/distributions/gamma.rs @@ -274,6 +274,47 @@ impl IndependentSample for FisherF { } } +/// The Student t distribution, `t(nu)`, where `nu` is the degrees of +/// freedom. +/// +/// # Example +/// +/// ```rust +/// use std::rand; +/// use std::rand::distributions::{StudentT, IndependentSample}; +/// +/// fn main() { +/// let t = StudentT::new(11.0); +/// let v = t.ind_sample(&mut rand::task_rng()); +/// println!("{} is from a t(11) distribution", v) +/// } +/// ``` +pub struct StudentT { + priv chi: ChiSquared, + priv dof: f64 +} + +impl StudentT { + /// Create a new Student t distribution with `n` degrees of + /// freedom. Fails if `n <= 0`. + pub fn new(n: f64) -> StudentT { + assert!(n > 0.0, "StudentT::new called with `n <= 0`"); + StudentT { + chi: ChiSquared::new(n), + dof: n + } + } +} +impl Sample for StudentT { + fn sample(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } +} +impl IndependentSample for StudentT { + fn ind_sample(&self, rng: &mut R) -> f64 { + let norm = *rng.gen::(); + norm * (self.dof / self.chi.ind_sample(rng)).sqrt() + } +} + #[cfg(test)] mod test { use rand::*; @@ -323,6 +364,16 @@ mod test { f.ind_sample(&mut rng); } } + + #[test] + fn test_t() { + let mut t = StudentT::new(11.0); + let mut rng = task_rng(); + for _ in range(0, 1000) { + t.sample(&mut rng); + t.ind_sample(&mut rng); + } + } } #[cfg(test)] diff --git a/src/libstd/rand/distributions/mod.rs b/src/libstd/rand/distributions/mod.rs index 261b77fb2456..a381ac35d30c 100644 --- a/src/libstd/rand/distributions/mod.rs +++ b/src/libstd/rand/distributions/mod.rs @@ -27,7 +27,7 @@ use rand::{Rng, Rand}; use clone::Clone; pub use self::range::Range; -pub use self::gamma::{Gamma, ChiSquared, FisherF}; +pub use self::gamma::{Gamma, ChiSquared, FisherF, StudentT}; pub use self::normal::{Normal, LogNormal}; pub use self::exponential::Exp;