Skip to content

Rayon and random number generator #398

@rohitjoshi

Description

@rohitjoshi

What is the best way to pass thread-safe/thread-local random number generator so we can execute distribution operation with multiple threads?

e.g . How can I run below code to generate normal distribution in parallel using rayon or alternate way?

fn normal(mu:f64, sigma: &Vec<f64>) -> Vec<f64> {
        let mut rng = thread_rng();
        let mut v = Vec::with_capacity(sigma.len());
        for i in 0..sigma.len() {
            let mut g = Normal::new(mu, sigma[i] ).unwrap();
            v.push(g.ind_sample(&mut rng));
        }
        v
    }

I tried using below code but due to mutable rng, it is not allowed.

fn normal(mu:f64, sigma: &Vec<f64>) -> Vec<f64> {
         let mut rng = thread_rng();
        let mut v = Vec::with_capacity(sigma.len());
        (0..sigma)
            .into_par_iter()
            .map(|_| {
              let mut g = Normal::new(mu, sigma[i] ).unwrap();
               g.ind_sample(&mut rng)
             })
            .collect_into_vec(&mut v);
          v
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    F-new-intFunctionality: new, within RandP-lowPriority: Low

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions