开发者

Why are my random numbers not so random?

开发者 https://www.devze.com 2023-01-24 19:32 出处:网络
int totalRecs = getTotalRecs(); // returns \'13\' int MAX_RECS_PER_LOOKUP = 10; Random rand = new Random();
int totalRecs = getTotalRecs(); // returns '13'
int MAX_RECS_PER_LOOKUP = 10;
Random rand = new Random();
int start = (totalRecs > Utl.MAX_RECS_PER_LOOKUP) ? rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP) : 0;
results = this.getNewRecs(filter, start, start+1);

I'm using this random number logic to retrieve records from the database based on their table row offset (start up to start+1).

But for some reason it keeps repeating the same numbers: start value of 0 and start value of 3.

I tried seeding the Rando开发者_如何学Pythonm object but it made no difference:

long seed = System.currentTimeMillis();
rand.setSeed(seed);


The rand.nextInt(n) method returns a value between 0 (inclusive) and n (exclusive).

In your code, if totalRecs is 13, and Utl.MAX_RECS_PER_LOOKUP is 10 (I am assuming this one based on the MAX_RECS_PER_LOOKUP value in your code snippet, but I may be wrong), then this code:

rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP);

should return a random number between 0 and 2.

I am not sure if this is what you actually want?


Make sure your inputs are valid.

Via debug compare values of

totalRecs Utl.MAX_RECS_PER_LOOKUP & start on the same iteration.

You are calling

rand.nextInt(totalRecs-Utl.MAX_RECS_PER_LOOKUP)

The only way you should "always" be getting 0 is if totalRecs = Utl.MAX_RECS_PER_LOOKUP However if the difference is only 1 then you will get back 0 or 1 randomly.


You could try java.security.SecureRandom

It seems to be a good alternative, and it inherits from java.util.Random

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号