简体   繁体   中英

How to scale pseudo random numbers to a specific range?

How would I scale random numbers to say 1-10 whithout loosing the randomness?

I know, just using % 10 is not a good idea.

And in addition, I need a seed value, so I can test on determinsitic numbers,

but I have not understood what value this seed should have and I how it influences the sequence.

Is there a difference if it is high or low ?

thanks in advance.

import java.util.Random;

Random random = new Random( yourSeed );
int randomInt = random.nextInt(10) + 1 ;

The seed has no other purpose than to give the PRNG a starting point. It is purely arbitrary and will not influence the distribution of the random numbers.

The nextGaussian() is different in that it returns floating point numbers distributed around a bell curve.

usually when trying to get a random value you'll use something like this:

public int getRandom( int min, int max )
{
    return (int) Math.round( Math.random() % (max - min) + min );
}

Or, as I just remembered from Stavr00's answer, use one of the built in functions from java.util.Random

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM