2012-12-17 50 views
3

閱讀其他文章我已經計算出我將不得不使用BigInteger在30到32位數字範圍內生成20,000個隨機數字。java在30到32位數字範圍內生成隨機數字

public BigInteger(int numBits, Random rnd) 

但是,這不允許數字的最小和最大範圍。

感謝

+0

一個簡單的解決辦法是'30'之間隨機選擇,'31'和'32'每次想要生成一個數字。 –

+0

20000號碼必須是唯一的嗎? – beny23

+0

@HunterMcMillen你將不得不使用加權隨機數字:有30位數字的31位數字的10倍。 – Bohemian

回答

2

如果要使用此功能,你可以做

public static BigInteger random(Random rand, BigInteger minValue, BigInteger maxValue) { 
    BigInteger range = maxValue.subtract(minValue).add(BigInteger.ONE); 
    int bits = range.bitLength(); 
    BigInteger ret; 
    do { 
     ret = new BigInteger(bits, rand); 
    } while(ret.compareTo(range) >= 0); 
    return ret.add(minValue); 
} 
+0

只是想知道是否代替循環'ret.mod(range).add(minValue )''會更好的表現明智比可能做多個呼叫到RNG – beny23

+0

這是可能的,如果您生成更多的位,以便結果不偏斜(所以每個數字都有一個合理的平等機會)您將不得不基準它看哪個更快。 –

+0

有意義,如果我還沒有upvoted,我現在會做... – beny23

相關問題