LevelDB求随机数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LevelDB求随机数相关的知识,希望对你有一定的参考价值。

LevelDB求随机数

util/random.h

#include <cstdint>

namespace leveldb {

// A very simple random number generator.  Not especially good at
// generating truly random bits, but good enough for our needs in this
// package.
class Random {
 private:
    //随机数种子
  uint32_t seed_;

 public:
    //构造函数设置随机数种子
    //种子不能是0或者0x7fffffff,不然后续求得的随机数全部是0
  explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) {
    // Avoid bad seeds.
    if (seed_ == 0 || seed_ == 2147483647L) {
      seed_ = 1;
    }
  }
    //求出下一个随机数,从这个函数可以知道,当随机数种子确定了,后面的一系列随机数全部就都已经确定了
  uint32_t Next() {
      //0x7fffffff
    static const uint32_t M = 2147483647L;  // 2^31-1
    static const uint64_t A = 16807;        // bits 14, 8, 7, 5, 2, 1, 0
    // We are computing
    //       seed_ = (seed_ * A) % M,    where M = 2^31-1
    //
    // seed_ must not be zero or M, or else all subsequent computed values
    // will be zero or M respectively.  For all other values, seed_ will end
    // up cycling through every number in [1,M-1]
    uint64_t product = seed_ * A;

    // Compute (product % M) using the fact that ((x << 31) % M) == x.
      //最高位+后面31位
    seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
    // The first reduction may overflow by 1 bit, so we may need to
    // repeat.  mod == M is not possible; using > allows the faster
    // sign-bit-based test.
    if (seed_ > M) {
      seed_ -= M;
    }
      //返回随机数,他也是下一个种子
    return seed_;
  }
  // Returns a uniformly distributed value in the range [0..n-1]
  // REQUIRES: n > 0
  uint32_t Uniform(int n) { return Next() % n; }

  // Randomly returns true ~"1/n" of the time, and false otherwise.
  // REQUIRES: n > 0
    //这个就是1/n的几率返回true
  bool OneIn(int n) { return (Next() % n) == 0; }

  // Skewed: pick "base" uniformly from range [0,max_log] and then
  // return "base" random bits.  The effect is to pick a number in the
  // range [0,2^max_log-1] with exponential bias towards smaller numbers.
    //首先求得[0,max_log]的一个随机数,然后求得[0,2^maxlog-1]的一个随机数
  uint32_t Skewed(int max_log) { return Uniform(1 << Uniform(max_log + 1)); }
};

}  // namespace leveldb

以上是关于LevelDB求随机数的主要内容,如果未能解决你的问题,请参考以下文章

leveldb学习:skiplist

[leveldb]0.源码编译及使用

[leveldb] 2.open操作介绍

LevelDB深入浅出之整体架构

LevelDB 概述

LevelDB是什么?为什么我们需要K-V存储?