1. 程式人生 > >隨機產生一個限定範圍的long型數字

隨機產生一個限定範圍的long型數字

最近抓取新浪微博的資料,需要產生一些隨機微博的ID。由於新浪微博的ID是一個16位的數字,所以在Java程式中要用long型來產生。並且,微博ID是有一定範圍的,如果不限定範圍,命中的概率會很低。這裡就需要限定產生隨機數的範圍。然而,在Java SDK中,只提供了一個產生整數的、可限定範圍的方法:

public int nextInt(int n) {
     if (n<=0)
                throw new IllegalArgumentException("n must be positive");

     if ((n & -n) == n)  // i.e., n is a power of 2
         return (int)((n * (long)next(31)) >> 31);

     int bits, val;
     do {
         bits = next(31);
         val = bits % n;
     } while(bits - val + (n-1) < 0);
     return val;
 }

看了一下官方文件,併到網上查閱了一些資料。認為如下實現是最好的獲得限制範圍的long型數字的方法:
public long nextLong(Random rng, long n) {
   // error checking and 2^x checking removed for simplicity.
   long bits, val;
   do {
      bits = (rng.nextLong() << 1) >>> 1;
      val = bits % n;
   } while (bits-val+(n-1) < 0L);
   return val;
}