Skip to content

Add randn to create an array of standard gaussian numbers. #147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ optional = true

[dependencies]
blas-sys = { version = "0.5", optional = true, default-features = false }

asprim = "0.1"
rand = "0.3"
# deprecated! use ndarray-rblas instead
rblas = { version = "0.0.13", optional = true }

Expand Down
31 changes: 31 additions & 0 deletions src/impl_constructors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@

//! Constructor methods for ndarray
//!
extern crate rand;
use self::rand::distributions::{Normal, IndependentSample};
use self::rand::{Rng};

extern crate asprim;
use self::asprim::AsPrim;
use libnum;

use imp_prelude::*;
Expand Down Expand Up @@ -252,3 +258,28 @@ impl<S, A, D> ArrayBase<S, D>
}

}

use super::NdFloat;

impl<S, A, D> ArrayBase<S, D>
where S: DataOwned<Elem=A>,
A: NdFloat+AsPrim,
D: Dimension,
{
pub fn randn_rng<R: Rng>(dim: D, rng: &mut R) -> ArrayBase<S, D>
{
let size = dim.size_checked().expect("Shape too large: overflow in size");
let normal = Normal::new(1.0, 0.0);
let iter = (0..size).map(|_| normal.ind_sample(rng).as_());
let arr = ArrayBase::from_iter(iter);
arr.into_shape(dim).unwrap()
}

pub fn randn(dim: D) -> ArrayBase<S, D>
{
// Use the thread_rng once to seed a fast, non-crypto grade rng.
// To use a crypto quality RNG, use randn_rng directly.
let mut rng = rand::weak_rng();
ArrayBase::<S, D>::randn_rng(dim, &mut rng)
}
}