biased 0.1.2

A Rust library for generating biased random numbers, useful for simulations and weighted selections. 一个用于生成偏向性随机数的 Rust 库,适用于模拟和加权选择场景。
Documentation
#![feature(doc_auto_cfg)]
#![feature(doc_cfg)]

use rand::Rng;

/// Generate a non-uniformly distributed random integer in the range [0, n).
/// The distribution is controlled by a bias parameter, which makes smaller integers more likely to be generated.
/// 生成一个在 [0, n) 区间内非均匀分布的随机整数。
/// 通过一个偏向参数 (bias) 来控制分布,使得数值越小的整数生成的概率越高。
///
/// # Arguments
///
/// * `n` - The upper bound (exclusive) for the random number. Must be a positive integer greater than 0.
///         - `n`: 随机数上限(不包含),必须是大于0的正整数。
/// * `bias` - The bias strength parameter. Must be a positive number.
///          - `bias > 1`: Smaller numbers are more likely. The larger the bias, the more skewed the result is towards 0.
///          - `bias = 1`: Approaches a standard uniform distribution.
///          - `0 < bias < 1`: Larger numbers are more likely.
///          - `bias`: 偏向强度参数,必须是正数。
///            - `bias > 1`: 数值越小概率越高。bias越大,结果越偏向0。
///            - `bias = 1`: 接近标准均匀分布。
///            - `0 < bias < 1`: 数值越大概率越高。
///
/// # Returns
///
/// A random integer in the [0, n) range.
/// 返回一个在 [0, n) 区间内的随机整数。
pub fn biased_random(n: u32, bias: f64) -> u32 {
  if n <= 1 {
    return 0;
  }

  // 1. Get a standard uniform random number in [0, 1).
  // 1. 获取一个 [0, 1) 之间的标准均匀分布随机数。
  let rng: f64 = rand::rng().random();

  // 2. "Warp" the distribution using a power function.
  //    When bias > 1, this pushes most of the results towards 0.
  // 2. 使用幂函数来“扭曲”这个分布。
  //    当 bias > 1 时,这个操作会把大部分结果值推向 0。
  let biased_rng = rng.powf(bias);

  // 3. Map the biased random number from the [0, 1) range to the integer range [0, n).
  // 3. 将 [0, 1) 范围内的偏向随机数映射到 [0, n) 的整数范围。
  (biased_rng * n as f64) as u32
}