3

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.

DylanJaide
  • 385
  • 1
  • 3
  • 13

5 Answers5

4

A short cast of an int works by bitwise truncation. As long as the integers are randomly distributed, the short values should be also - yes.

From the Java Language Specification 5.1.3:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.

int has 32 bits, short has 16. Essentially the conversion is the same as adding (or subtracting) 65536 (which is 2 to the power of 16) until the value is in the range representable by short. Thus, there are exactly 65536 int values which map to each possible short value.

davmac
  • 20,150
  • 1
  • 40
  • 68
3

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.

biziclop
  • 48,926
  • 12
  • 77
  • 104
1

A good solution to avoid error is :

Random rand = new Random(int seed);
short s = (short) rand.nextInt(Short.MAX_VALUE + 1);

If you also need negative short :

short s = (short) rand.nextInt(Short.MAX_VALUE - Short.MIN_VALUE + 1) + Short.MIN_VALUE;

A fastest solution :

short s = (short) random.nextInt(1 << 16); // any short
short s = (short) random.nextInt(1 << 15); // any non-negative short
Alexandre Cartapanis
  • 1,513
  • 3
  • 15
  • 19
-1

The number will be still random, but you can have problem with different max/min values of this number, for more info, look at first answer here here

Community
  • 1
  • 1
Tony Danilov
  • 430
  • 3
  • 11
  • 22
-1

I think this will not work because an int is a lot bigger than a short.

Just take a random float or double (the values are between [-1;1]) and multiply them by the max value of a short:

short i= (short) rand.nextFloat() * Short.MAX_VALUE;