a_b
a_b

Reputation: 1918

Create random 2d array in rust

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

Answers (1)

Ömer Erden
Ömer Erden

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]]
}

Dependency

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

Related Questions