numas/factory/
random.rs

1extern crate rand;
2
3use self::rand::{
4    distributions::{
5        Uniform,
6        Distribution,
7    },
8    Rng,
9};
10
11use array::Array;
12
13
14/// Creates new array of given shape filled with random values from given distribution
15///
16/// # Arguments
17///
18/// * `distr` - distribution of random values
19/// * `shape` - shape of new array
20pub fn random_from_distribution<T, D>(distr: D, shape: Vec<i32>) -> Array<T>
21    where T: Copy, D: Distribution<T>
22{
23    let mut rng = rand::thread_rng();
24
25    let len: i32 = shape.iter().product();
26    let data: Vec<T> = rng.sample_iter(&distr).take(len as usize).collect();
27
28    return Array::new(data, shape);
29}
30
31/// Creates new array of given shape filled with random values between given range
32///
33/// # Arguments
34///
35/// * `from` - start of range
36/// * `to` - end of range
37/// * `shape` - shape of new array
38#[inline]
39pub fn random_range<T>(from: T, to: T, shape: Vec<i32>) -> Array<T>
40    where T: rand::distributions::uniform::SampleUniform + Copy
41{
42    return random_from_distribution(Uniform::new::<T, T>(from, to), shape);
43}
44
45/// Creates new array of given shape filled with random values from between 0 and 1 (floating point numbers only)
46///
47/// # Arguments
48///
49/// * `shape` - shape of new array
50#[inline]
51pub fn random<T>(shape: Vec<i32>) -> Array<T>
52    where T: rand::distributions::uniform::SampleUniform + From<u8> + Copy
53{
54    return random_range::<T>(T::from(0), T::from(1), shape);
55}
56