pub fn new_random_vec<T, D, R>(
n: usize,
distribution: &D,
rng: &mut R,
) -> Vec<T>
Expand description
Generates a Vec<T>
of a specified length with random values.
This function leverages the RandomSampleFromF64
trait to provide a universal way
to create a vector of random numbers for any supported scalar type, including
primitive types like f64
and Complex<f64>
, as well as validated types
like RealValidated
and ComplexValidated
.
§Parameters
n
: The number of random values to generate in the vector.distribution
: A reference to any distribution from therand
crate that implementsDistribution<f64>
(e.g.,Uniform
,StandardNormal
).rng
: A mutable reference to a random number generator that implementsRng
.
§Type Parameters
T
: The scalar type of the elements in the returned vector. Must implementRandomSampleFromF64
.D
: The type of the distribution.R
: The type of the random number generator.
§Example
use num_valid::{new_random_vec, RealNative64StrictFinite};
use rand::{distr::Uniform, rngs::StdRng, SeedableRng};
use try_create::IntoInner;
let seed = [42; 32]; // Use a fixed seed for a reproducible example
// Generate a vector of random f64 values.
let mut rng_f64 = StdRng::from_seed(seed);
let uniform = Uniform::new(-10.0, 10.0).unwrap();
let f64_vec: Vec<f64> = new_random_vec(3, &uniform, &mut rng_f64);
// Generate a vector of random validated real numbers using the same seed.
let mut rng_validated = StdRng::from_seed(seed);
let validated_vec: Vec<RealNative64StrictFinite> = new_random_vec(3, &uniform, &mut rng_validated);
assert_eq!(f64_vec.len(), 3);
assert_eq!(validated_vec.len(), 3);
// The underlying numerical values should be identical because the RNG was seeded the same.
assert_eq!(&f64_vec[0], validated_vec[0].as_ref());
assert_eq!(&f64_vec[1], validated_vec[1].as_ref());
assert_eq!(&f64_vec[2], validated_vec[2].as_ref());