I am trying to create a random 2D array in which each entry is 0 with probability p
and 1 otherwise. In python, numpy makes it simple:
rand_arr = (np.random.rand(nrows, ncols) < p).astype(np.dtype('uint8'))
In rust, I wrote something like this
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 rand_arr = data_round_errors.mapv(|b| if b { 1 } else { 0 });
});
This is awfully slow. About 30 times slower than the python version! Which tells me I am doing something wrong. How can I write a faster implementation of this?
Aucun commentaire:
Enregistrer un commentaire