Skip to content

Commit

Permalink
Merge pull request #7 from dancixx/dev
Browse files Browse the repository at this point in the history
feat: make rand complex to multithread
  • Loading branch information
dancixx authored Sep 10, 2024
2 parents ed0c2bc + 030c06a commit 8f3ea9c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "stochastic-rs"
version = "0.7.0"
version = "0.7.1"
edition = "2021"
license = "MIT"
description = "A Rust library for stochastic processes"
Expand Down
10 changes: 10 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,14 @@ fn main() {
let sum: f32 = runs.iter().sum();
let average = sum / runs.len() as f32;
println!("Average time: {}", average);

let start = std::time::Instant::now();
let fbm = Fbm::new(0.75, 10000, Some(1.0), Some(1000));
let data = fbm.sample_par();
println!("Data: {:?}", data);
let duration = start.elapsed();
println!(
"Time elapsed in expensive_function() is: {:?}",
duration.as_secs_f32()
);
}
24 changes: 18 additions & 6 deletions src/noises/fgn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! The `FgnFft` struct provides methods to generate fractional Gaussian noise (FGN)
//! using the Fast Fourier Transform (FFT) approach.

use std::sync::Arc;
use std::sync::{Arc, Mutex};

use crate::utils::Generator;
use ndarray::parallel::prelude::*;
Expand Down Expand Up @@ -101,11 +101,23 @@ impl Generator for FgnFft {
/// let sample = fgn_fft.sample();
/// ```
fn sample(&self) -> Array1<f64> {
let rnd = Array1::<Complex<f64>>::random(
2 * self.n,
ComplexDistribution::new(StandardNormal, StandardNormal),
);
let fgn = &*self.sqrt_eigenvalues * &rnd;
let num_threads = rayon::current_num_threads();
let chunk_size = (2 * self.n) / num_threads;
let rnd = Arc::new(Mutex::new(Array1::<Complex<f64>>::zeros(2 * self.n)));

(0..num_threads).into_par_iter().for_each(|i| {
let chunk = Array1::<Complex<f64>>::random(
chunk_size,
ComplexDistribution::new(StandardNormal, StandardNormal),
);

let mut result_lock = rnd.lock().unwrap();
result_lock
.slice_mut(s![i * chunk_size..(i + 1) * chunk_size])
.assign(&chunk);
});

let fgn = &*self.sqrt_eigenvalues * &*rnd.lock().unwrap();
let mut fgn_fft = Array1::<Complex<f64>>::zeros(2 * self.n);
ndfft(&fgn, &mut fgn_fft, &*self.fft_handler, 0);
let scale = (self.n as f64).powf(-self.hurst) * self.t.powf(self.hurst);
Expand Down

0 comments on commit 8f3ea9c

Please sign in to comment.