我正在尝试创建一个随机 2D 数组,其中每个条目的概率为 0 p,否则为 1。在 python 中,numpy 使其变得简单:
rand_arr = (np.random.rand(nrows, ncols) < p).astype(np.dtype('uint8'))
Run Code Online (Sandbox Code Playgroud)
在 Rust 中,我写了这样的东西
use rand::Rng;
use rand::distributions::Bernoulli;
use ndarray::{Array2};
// Create a random number generator
let mut rng = rand::thread_rng();
// Create a Bernoulli distribution with the given probability
let bernoulli = Bernoulli::new(p).unwrap();
// Generate a 2D array of random boolean values using the Bernoulli distribution
let rand_arr: Array2<bool> = Array2::from_shape_fn((nrows, ncols), |_| {
rng.sample(bernoulli)
});
// convert bools to 0 and 1
let …Run Code Online (Sandbox Code Playgroud)