Search code examples
javarandomcastingintshort

Does casting random integers to short give a uniform distribution?


As the title explains, I am looking to generate a series of random short values. Because there is no Random.nextShort() function, the easiest way to do what I want seems to be to cast integers to short, using:

Random rand = new Random(int seed);
(short) rand.nextInt()

However, I don't fully understand how this casting takes place, and so I cannot be sure that the resulting short values would still be random. Is this the case? Thanks in advance.


Solution

  • The canonical way is to do short result = (short)(rand.nextInt(Short.MAX_VALUE-Short.MIN_VALUE+1) + Short.MIN_VALUE). The reason for this is that you want a number from a range that spans Short.MAX_VALUE-Short.MIN_VALUE+1 values, and starts at Short.MIN_VALUE.

    Simple truncation may be enough fort short (and if speed matters to you, it's probably also faster), but this approach works for any range.

    Let's say you want a random number between -5 and 12 (both inclusive), you will then call rand.nextInt(12-(-5)+1)+(-5), or if you simplify all the calculations: rand.nextInt(18)-5.