Skip to main content

sample_normal_batch

Function sample_normal_batch 

Source
pub fn sample_normal_batch<F>(
    n: usize,
    mean: F,
    std_dev: F,
    seed: Option<u64>,
) -> StatsResult<Array1<F>>
Expand description

Generate n independent samples from N(mean, std_dev²) using a SIMD-accelerated Box-Muller transform.

The Box-Muller transform converts pairs of independent U(0, 1) random variables (u₁, u₂) into pairs of independent standard-normal variates:

z₀ = √(−2 ln u₁) · cos(2π u₂)
z₁ = √(−2 ln u₁) · sin(2π u₂)

Both ln, sqrt, cos, and sin are evaluated via SIMD intrinsics from scirs2_core when the batch is large enough. The result is then scaled by std_dev and shifted by mean using a fused-multiply-add pass.

§Arguments

  • n — Number of samples to generate.
  • mean — Location parameter of the Normal distribution.
  • std_dev — Scale parameter (must be positive).
  • seed — Optional RNG seed for reproducibility.

§Errors

Returns StatsError::InvalidArgument when n == 0 or std_dev <= 0.

§Examples

use scirs2_stats::sample_normal_batch;

let samples = sample_normal_batch::<f64>(1_000, 0.0, 1.0, Some(42))
    .expect("sampling failed");
assert_eq!(samples.len(), 1_000);

// Empirical mean should be close to 0
let mean: f64 = samples.sum() / samples.len() as f64;
assert!(mean.abs() < 0.15);