1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
extern crate rand;

use self::rand::{
    distributions::{
        Uniform,
        Distribution,
    },
    Rng,
};

use array::Array;


/// Creates new array of given shape filled with random values from given distribution
///
/// # Arguments
///
/// * `distr` - distribution of random values
/// * `shape` - shape of new array
pub fn random_from_distribution<T, D>(distr: D, shape: Vec<i32>) -> Array<T>
    where T: Copy, D: Distribution<T>
{
    let mut rng = rand::thread_rng();

    let len: i32 = shape.iter().product();
    let data: Vec<T> = rng.sample_iter(&distr).take(len as usize).collect();

    return Array::new(data, shape);
}

/// Creates new array of given shape filled with random values between given range
///
/// # Arguments
///
/// * `from` - start of range
/// * `to` - end of range
/// * `shape` - shape of new array
#[inline]
pub fn random_range<T>(from: T, to: T, shape: Vec<i32>) -> Array<T>
    where T: rand::distributions::uniform::SampleUniform + Copy
{
    return random_from_distribution(Uniform::new::<T, T>(from, to), shape);
}

/// Creates new array of given shape filled with random values from between 0 and 1 (floating point numbers only)
///
/// # Arguments
///
/// * `shape` - shape of new array
#[inline]
pub fn random<T>(shape: Vec<i32>) -> Array<T>
    where T: rand::distributions::uniform::SampleUniform + From<u8> + Copy
{
    return random_range::<T>(T::from(0), T::from(1), shape);
}