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
57
58
59
60
61
62
63
64
65
66
use rand::{Rng, SeedableRng, StdRng};
use rand::distributions::range::SampleRange;
use num::traits::Float;
use std::f64;
use tensor::Tensor;
use traits::NumericTrait;
use math;
pub struct RandomState {
rng: StdRng,
}
impl RandomState {
pub fn new(seed: usize) -> RandomState {
let ss: &[_] = &[seed];
RandomState{rng: SeedableRng::from_seed(ss)}
}
pub fn uniform<T>(&mut self, low: T, high: T, shape: &[usize]) -> Tensor<T>
where T: NumericTrait + SampleRange {
let mut t = Tensor::zeros(shape);
{
let n = t.size();
let mut data = t.slice_mut();
for i in 0..n {
data[i] = self.rng.gen_range::<T>(low, high);
}
}
t
}
pub fn normal<T>(&mut self, shape: &[usize]) -> Tensor<T>
where T: NumericTrait + SampleRange + Float {
let u1 = self.uniform(T::zero(), T::one(), shape);
let u2 = self.uniform(T::zero(), T::one(), shape);
let minustwo = Tensor::fscalar(-2.0);
let twopi = Tensor::fscalar(2.0 * f64::consts::PI);
math::sqrt(math::ln(u1) * &minustwo) * &math::cos(u2 * &twopi)
}
}