LEVELDB source analysis of the seven: Random

Source: Internet
Author: User
I. Principle:
The pseudo-random number generation algorithm in C language is actually using "linear and congruential". The specific calculations are as follows:
Seed = (Seed * A + C)% M
where a,c,m are constants (usually take prime numbers). When c=0, it is called multiply the same congruential.
Suppose we define a random number function:
void rand (int &seed)
{
    seed = (seed * A + C)% M;
}
Each call to the RAND function produces a random value assignment to seed, which shows that a recursive sequence is actually generated with the RAND function, and that all values originate from the original seed. So when the initial seed takes the same time, the resulting sequence is the same.

As we call seed, a pseudo-random number is commonly used to make m as large as possible. For example, for a 32-bit machine, select m=2^31-1=2147483647 and a=7^5=16807 to get the best results.


two. Code implementation:
Now let's see how random numbers in Leveldb are implemented:

In the random class, A is 16807,m to 2147483647,c of 0;

#ifndef storage_leveldb_util_random_h_ #define Storage_leveldb_util_random_h_ #include <stdint.h> namespace Lev  ELDB {//A very simple random number generator.
    
    Not the especially good at//generating truly random bits, but good the enough for we needs in this//package.
    Class Random {private:uint32_t seed_; Public://0x7fffffffu = = 2147483647L = = 2^31-1 = 01111111 11111111 11111111 11111111//Expression S & 0x7ff  Fffffu, ensure that the resulting value is within the range of [0,2147483647] explicit Random (uint32_t s): Seed_ (S & 0x7fffffffu) {//
            Avoid Bad Seeds. Seed_ cannot be zero or m, otherwise all subsequent computed values will be zero or m if (Seed_ = = 0 | | seed_ = = 2147483647L) {seed_ =
            1;
            }}//16807 random number uint32_t Next () {//01111111 11111111 11111111 11111111   static const uint32_t M = 2147483647L;
            2^31-1//0100 0001 1010 0111static const uint64_t A = 16807; Bits, 8, 7, 5, 2, 1, 0//We are computing//Seed_ = (seed_ * A)% M, where M = 2^  31-1////Seed_ must not being zero or M, or else all subsequent computed values//would  be zero or M respectively. For all and values, Seed_ will end//up cycling through every number in [1,m-1]//here Seed_*a set
            For the random number generator product, note that the product is 64-bit.
            Then seed_=product% M is equivalent to getting a random number in the size of [1,m-1].
            uint64_t Product = Seed_ * A;
            Compute (product% m) using the fact that ((x << a)% M) = = x.
            For product% M, the operation is optimized using (product >> +) + (product & M)//Considering the right shift and the cost of the operation is much less than the take-away operation. The following equation is used ((x <<)% M) = = x Technique (proof of equation see section III)//product%m = static_cast<uint32_t> (Product &GT;&G T + (product & M)) See section Fourth Seed_ = static_cast<uint32_t> (Product >> 31) + (product & M));  The first reduction may be overflow by 1 bits, so we may be 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]//Returns the uniform distribution values within 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 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. Bias: Uniform (max_log + 1) value range is [0,max_log],1 left shift [0,max_LOG] Get//range is [1,2^max_log],uniform ([1,2^max_log]) The resulting range is [0,2^max_log-1] uint32_t skewed (int max_log)
        {return Uniform (1 << Uniform (Max_log + 1));
    
}
    }; }//Namespace Leveldb
three. Proof equation (x<<31)%M = = X is established. where M equals 2^31-1
Evaluates the expression to the left (x << a)% M, since x<<31 equals x*2^31,
Then (x << a)% m= (x*2^31)%m= (x + x* (2^31-1))%m= (x + x*m)%m=x


four. Proof equation (product%m) = = (product>>31) + (product&m), where M equals 2^31-1
Because the product type is uint64_t, you can decompose product from left to right into high 33-bit and low 31-bit, as follows:
High 33 bit Low 31
(product>>31) <<31+product&m
(product>>31) <<31+product&m= (product>>31) *2^31+product&m=seed_*a, since Seed_ and A are both smaller than M, so ( product>>31) less than M
Product%m = ((product>>31) <<31+product&m)%M
Modulo operation satisfies the allocation rate (A+B)%c= (a%c+b%c)%c
Product%m = ((product>>31) *2^31+product&m)%M
Product%m = (((product>>31) <<31)%m+ (product&m)%M)%M
According to section III ((PRODUCT&GT;&GT;31) <<31)%m= (product>>31), first assume product&m is less than M
Product%m = (product>>31+product&m)%M
Product%m = product>>31+product&m, first assuming (product>>31+product&m) is less than M.
However, a low 31-bit value of product&m may be equal to M, which causes the Product%m value to be greater than M error (certainly less than 2M), but the following security measures are taken in the source code.
Seed_ = static_cast<uint32_t> (product >> + (product & M));
if (Seed_ > M)
{
Seed_ = M;
}


Reference Link: https://yq.aliyun.com/articles/2271

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.