34

I am trying to generate random integers over the range (-32768, 32767) of the primitive data type short. The java Random object only generates positive numbers. How would I go about randomly creating numbers on that interval? Thanks.

jww
  • 83,594
  • 69
  • 338
  • 732
user455497
  • 587
  • 2
  • 5
  • 12
  • This remind me about Rnd() of VB, it returns value in [0,1) only. – pinichi Oct 15 '10 at 02:36
  • 1
    Possible duplicate of [How to generate random integers within a specific range in Java?](https://stackoverflow.com/q/363681/608639) – jww Jan 02 '19 at 17:59

8 Answers8

58

You random on (0, 32767+32768) then subtract by 32768

pinichi
  • 2,159
  • 15
  • 17
24
Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);
Truth
  • 466
  • 1
  • 4
  • 11
  • scala> def myNextPositiveNumber :Int = { r.nextInt(65536)-32768} myNextPositiveNumber: Int scala> println(myNextPositiveNumber) -17761 scala> println(myNextPositiveNumber) -26558 scala> scala> println(myNextPositiveNumber) -17758 scala> println(myNextPositiveNumber) -823 scala> println(myNextPositiveNumber) 17370 – aironman Feb 21 '17 at 12:06
6
public static int generatRandomPositiveNegitiveValue(int max , int min) {
    //Random rand = new Random();
    int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
    return ii;
}
duggu
  • 35,841
  • 11
  • 112
  • 110
  • Where are you using rand? – WowBow Dec 19 '13 at 04:20
  • Let's take, for example, min = 2 and max = 4. So in case of lowest random number, let's say 0.001, * ((4 - (- 2)) + 1) = 7 * 0.001 = (int) 0.007 = 0 and then -2 + 0 = -2. So we got -2 when actually the minimum was 2. Something in this formula went wrong. – yoni Jun 21 '15 at 17:40
4

Generate numbers between 0 and 65535 then just subtract 32768

jcopenha
  • 3,867
  • 1
  • 14
  • 14
3

This is an old question I know but um....

n=n-(n*2)
Ethan
  • 338
  • 2
  • 7
  • 22
1

([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

example:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));
Russ Jackson
  • 1,675
  • 1
  • 15
  • 12
0

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

UP209D
  • 1
  • 1
0

In case folks are interested in the double version (note this breaks down if passed MAX_VALUE or MIN_VALUE):

private static final Random generator = new Random();
public static double random(double min, double max) {
    return min + (generator.nextDouble() * (max - min));
 }
Brian
  • 11