byzhang / leveldb

Automatically exported from code.google.com/p/leveldb
BSD 3-Clause "New" or "Revised" License
0 stars 0 forks source link

Random never return 0 #202

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
In util/ random.h, we are computing  seed_ = (seed_ * A) % M,    where M = 
2^31-1, and the seed_ cannot be zero.

So, Random::Next() function never returns zero.

The member function of this class

 uint32_t Uniform(int n) { return Next() % n; }

returns a uniformly distributed value in the range [1..n-1] , not [0..n-1]

patch:
change the last line of  function Next()  from 
 return seed_;
to 
 return seed_ - 1;

Original issue reported on code.google.com by me@sunchangming.com on 29 Aug 2013 at 4:25

GoogleCodeExporter commented 9 years ago
Random::Next() may never return 0, but it can return n and 2*n and 3*n etc.  As 
a result the values returned are [0..n-1] as stated.  For values of n < sqrt(m) 
the "uniformly distributed" clause is also valid.

Original comment by napadan...@gmail.com on 23 Oct 2013 at 5:02