c++ - 基于随机比特流生成随机浮点值

标签 c++ algorithm random

给定一个随机源(随机比特流的生成器),如何生成给定范围内均匀分布的随机浮点值?

假设我的随机源看起来像这样:

unsigned int GetRandomBits(char* pBuf, int nLen);

我想实现

double GetRandomVal(double fMin, double fMax);

注意事项:

  • 我不希望结果精度受到限制(例如只有 5 位数)。
  • 必须严格统一分配
  • 我不是要引用现有的图书馆。我想知道如何从头开始实现。
  • 对于伪代码/代码,C++ 将是最重要的

最佳答案

我认为我永远不会相信您真的需要这个,但写起来很有趣。

#include <stdint.h>

#include <cmath>
#include <cstdio>

FILE* devurandom;

bool geometric(int x) {
  // returns true with probability min(2^-x, 1)
  if (x <= 0) return true;
  while (1) {
    uint8_t r;
    fread(&r, sizeof r, 1, devurandom);
    if (x < 8) {
      return (r & ((1 << x) - 1)) == 0;
    } else if (r != 0) {
      return false;
    }
    x -= 8;
  }
}

double uniform(double a, double b) {
  // requires IEEE doubles and 0.0 < a < b < inf and a normal
  // implicitly computes a uniform random real y in [a, b)
  // and returns the greatest double x such that x <= y
  union {
    double f;
    uint64_t u;
  } convert;
  convert.f = a;
  uint64_t a_bits = convert.u;
  convert.f = b;
  uint64_t b_bits = convert.u;
  uint64_t mask = b_bits - a_bits;
  mask |= mask >> 1;
  mask |= mask >> 2;
  mask |= mask >> 4;
  mask |= mask >> 8;
  mask |= mask >> 16;
  mask |= mask >> 32;
  int b_exp;
  frexp(b, &b_exp);
  while (1) {
    // sample uniform x_bits in [a_bits, b_bits)
    uint64_t x_bits;
    fread(&x_bits, sizeof x_bits, 1, devurandom);
    x_bits &= mask;
    x_bits += a_bits;
    if (x_bits >= b_bits) continue;
    double x;
    convert.u = x_bits;
    x = convert.f;
    // accept x with probability proportional to 2^x_exp
    int x_exp;
    frexp(x, &x_exp);
    if (geometric(b_exp - x_exp)) return x;
  }
}

int main() {
  devurandom = fopen("/dev/urandom", "r");
  for (int i = 0; i < 100000; ++i) {
    printf("%.17g\n", uniform(1.0 - 1e-15, 1.0 + 1e-15));
  }
}

关于c++ - 基于随机比特流生成随机浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5015133/

相关文章:

c++ - 不明白这个返回类型?

C++ 错误 C2511 : overloaded member function not found in 'Sprite'

ios - 显示插页式广告 A 'Fraction Of The Time' - 即并非每次

c++ - 我应该如何在没有反复试验的情况下解决这个递归问题

java - 计算 2 的 k 次方

python - 将一列随机数添加到 dask 数据帧的正确方法

algorithm - 关于纯随机数系列的困惑

c++ - Winapi 对话框在 Windows XP 上损坏

c++ - 在类中存储 Lambda

algorithm - 用固定值填充 n 个位置的方法