ndtensor/impls/
impl_tensor_rand.rs

1/*
2    appellation: impl_tensor_rand <module>
3    authors: @FL03
4*/
5use crate::tensor::TensorBase;
6
7use ndarray::{DataOwned, Dimension, ShapeBuilder};
8use rand::RngCore;
9use rand_distr::Distribution;
10
11impl<A, S, D> TensorBase<S, D>
12where
13    D: Dimension,
14    S: DataOwned<Elem = A>,
15{
16    /// generate a new tensor with the given shape and randomly initialized values
17    pub fn random<Sh, Ds>(shape: Sh, distr: Ds) -> Self
18    where
19        Ds: Distribution<A>,
20        Sh: ShapeBuilder<Dim = D>,
21    {
22        use rand::{SeedableRng, rngs::SmallRng};
23        Self::random_using(shape, distr, &mut SmallRng::from_rng(&mut rand::rng()))
24    }
25    /// randomly initializes a tensor with the given shape using the provided distribution and 
26    /// random number generator
27    pub fn random_using<Sh, Ds, R>(shape: Sh, distr: Ds, rng: &mut R) -> Self
28    where
29        R: RngCore + ?Sized,
30        Ds: Distribution<A>,
31        Sh: ShapeBuilder<Dim = D>,
32    {
33        Self::from_shape_fn(shape, |_| distr.sample(rng))
34    }
35    /// Randomly initializes a tensor with the given shape using the provided distribution
36    pub fn random_with<Dst, Sh>(shape: Sh, distr: Dst) -> Self
37    where
38        S: DataOwned,
39        Sh: ShapeBuilder<Dim = D>,
40        Dst: Clone + Distribution<A>,
41    {
42        Self::random_using(shape, distr, &mut rand::rng())
43    }
44}