Reputation: 1918
How would you create a random 2d array in rust equivalent to numpy's:
np.random.rand(3, 2)
array([[0.81103811, 0.51529836],
[0.02255365, 0.28580315],
[0.97909856, 0.05897878]])
Upvotes: 0
Views: 400
Reputation: 8793
You can use ndarray-rand crate which is an integration of rand and ndarray crate.
This is the equivalent code for np.random.rand(3, 2)
use ndarray::Array;
use ndarray_rand::{rand_distr::Standard, RandomExt};
fn main() {
println!("{:.4}", Array::<f64, _>::random((3, 2), Standard));
// Example Output:
//[[0.3762, 0.5176],
// [0.0949, 0.3432],
// [0.8329, 0.5704]]
}
Array::<f64, _>
can be changed to different types like
Array::<u64, _>
to get random value from u64 set.Uniform
distribution can be used to earn flexibility to have custom rangenumpy.random.Generator.choice
)Since ndarray-rand
is a Random Extension for ndarray
crate you'll need ndarray
crate in your project, your Cargo.toml should look like this:
[dependencies]
ndarray-rand = "*" #todo select compatible version to ndarray vice-versa
ndarray = "*" #todo ...
Upvotes: 1