webrtc中的随机数生成代码

   说明,代码摘取自webrtc中的代码库,随机数生成算法:

random.h

#ifndef __RANDOM_H__
#define __RANDOM_H__
#include<limits>
#include<stdint.h>
#include<math.h>
class Random {
 public:
  // TODO(tommi): Change this so that the seed can be initialized internally,
  // e.g. by offering two ways of constructing or offer a static method that
  // returns a seed that's suitable for initialization.
  // The problem now is that callers are calling clock_->TimeInMicroseconds()
  // which calls TickTime::Now().Ticks(), which can return a very low value on
  // Mac and can result in a seed of 0 after conversion to microseconds.
  // Besides the quality of the random seed being poor, this also requires
  // the client to take on extra dependencies to generate a seed.
  // If we go for a static seed generator in Random, we can use something from
  // webrtc/base and make sure that it works the same way across platforms.
  // See also discussion here: https://codereview.webrtc.org/1623543002/
  explicit Random(uint64_t seed);

  // Return pseudo-random integer of the specified type.
  // We need to limit the size to 32 bits to keep the output close to uniform.
  template <typename T>
  T Rand() {
    static_assert(std::numeric_limits<T>::is_integer &&
                      std::numeric_limits<T>::radix == 2 &&
                      std::numeric_limits<T>::digits <= 32,
                  "Rand is only supported for built-in integer types that are "
                  "32 bits or smaller.");
    return static_cast<T>(NextOutput());
  }

  // Uniformly distributed pseudo-random number in the interval [0, t].
  uint32_t Rand(uint32_t t);

  // Uniformly distributed pseudo-random number in the interval [low, high].
  uint32_t Rand(uint32_t low, uint32_t high);

  // Uniformly distributed pseudo-random number in the interval [low, high].
  int32_t Rand(int32_t low, int32_t high);

  // Normal Distribution.
  double Gaussian(double mean, double standard_deviation);

  // Exponential Distribution.
  double Exponential(double lambda);

 private:
  // Outputs a nonzero 64-bit random number.
  uint64_t NextOutput() {
    state_ ^= state_ >> 12;
    state_ ^= state_ << 25;
    state_ ^= state_ >> 27;
    //RTC_DCHECK(state_ != 0x0ULL);
    return state_ * 2685821657736338717ull;
  }

  uint64_t state_;

  RTC_DISALLOW_IMPLICIT_CONSTRUCTORS(Random);
};

// Return pseudo-random number in the interval [0.0, 1.0).
template <>
float Random::Rand<float>();

// Return pseudo-random number in the interval [0.0, 1.0).
template <>
double Random::Rand<double>();

// Return pseudo-random boolean value.
template <>
bool Random::Rand<bool>();

#endif // __RANDOM_H__
random.cc

#include"random.h"
Random::Random(uint64_t seed) {
  //RTC_DCHECK(seed != 0x0ull);
  state_ = seed;
}

uint32_t Random::Rand(uint32_t t) {
  // Casting the output to 32 bits will give an almost uniform number.
  // Pr[x=0] = (2^32-1) / (2^64-1)
  // Pr[x=k] = 2^32 / (2^64-1) for k!=0
  // Uniform would be Pr[x=k] = 2^32 / 2^64 for all 32-bit integers k.
  uint32_t x = NextOutput();
  // If x / 2^32 is uniform on [0,1), then x / 2^32 * (t+1) is uniform on
  // the interval [0,t+1), so the integer part is uniform on [0,t].
  uint64_t result = x * (static_cast<uint64_t>(t) + 1);
  result >>= 32;
  return result;
}

uint32_t Random::Rand(uint32_t low, uint32_t high) {
  //RTC_DCHECK(low <= high);
  return Rand(high - low) + low;
}

int32_t Random::Rand(int32_t low, int32_t high) {
  //RTC_DCHECK(low <= high);
  // We rely on subtraction (and addition) to be the same for signed and
  // unsigned numbers in two-complement representation. Thus, although
  // high - low might be negative as an int, it is the correct difference
  // when interpreted as an unsigned.
  return Rand(high - low) + low;
}

template <>
float Random::Rand<float>() {
  double result = NextOutput() - 1;
  result = result / 0xFFFFFFFFFFFFFFFEull;
  return static_cast<float>(result);
}

template <>
double Random::Rand<double>() {
  double result = NextOutput() - 1;
  result = result / 0xFFFFFFFFFFFFFFFEull;
  return result;
}

template <>
bool Random::Rand<bool>() {
  return Rand(0, 1) == 1;
}

double Random::Gaussian(double mean, double standard_deviation) {
  // Creating a Normal distribution variable from two independent uniform
  // variables based on the Box-Muller transform, which is defined on the
  // interval (0, 1]. Note that we rely on NextOutput to generate integers
  // in the range [1, 2^64-1]. Normally this behavior is a bit frustrating,
  // but here it is exactly what we need.
  const double kPi = 3.14159265358979323846;
  double u1 = static_cast<double>(NextOutput()) / 0xFFFFFFFFFFFFFFFFull;
  double u2 = static_cast<double>(NextOutput()) / 0xFFFFFFFFFFFFFFFFull;
  return mean + standard_deviation * sqrt(-2 * log(u1)) * cos(2 * kPi * u2);
}

double Random::Exponential(double lambda) {
  double uniform = Rand<double>();
  return -log(uniform) / lambda;
}

真随机数的获取在linux可以对设备/dev/urandom进行读取,在windows下则可以调用RtlGenRandom。

还可以采用mt19937算法生成。

C++代码如下:

#include <random>
#include <iostream>

struct MT19937 {
private:
    static std::mt19937_64 rng;
public:
    // This is equivalent to srand().
    static void seed(uint64_t new_seed = std::mt19937_64::default_seed) {
        rng.seed(new_seed);
    }

    // This is equivalent to rand().
    static uint64_t get() {
        return rng();
    }
   static double get_double()
    {
        double result=rng();
        return result/std::numeric_limits<uint64_t>::max();

    }
 };

std::mt19937_64 MT19937::rng;


int main() {
    MT19937::seed(/*put your seed here*/);

    for (int i = 0; i < 10; ++ i)
        std::cout << MT19937::get() << std::endl;
}


[1]Redis源码中看伪随机数生成算法

[2]Java如何利用Math.random()产生泊松分布随机数

[3]c库的rand/random随机数产生函数性能差?

[4]【C/C++】生成64位随机数

[5]C语言生成32位和64位随机数算法

[6]C语言版本mt19937-64.c








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值