How to generate random positive and negative numbers in Java

110,835

Solution 1

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

Solution 2

Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);

Solution 3

public static int generatRandomPositiveNegitiveValue(int max , int min) {
    //Random rand = new Random();
    int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
    return ii;
}

Solution 4

Generate numbers between 0 and 65535 then just subtract 32768

Solution 5

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

n=n-(n*2)
Share:
110,835
user455497
Author by

user455497

Updated on January 03, 2020

Comments

  • user455497
    user455497 over 4 years

    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.

  • WowBow
    WowBow over 10 years
    Where are you using rand?
  • yoni
    yoni almost 9 years
    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.
  • Renato Probst
    Renato Probst almost 9 years
    This won't work. 3 = 3 - (3*2), 3 = -6.
  • Admin
    Admin almost 9 years
    Wrong. Order of operations.
  • GelatinFox
    GelatinFox almost 9 years
    Nope, it still wont work. How are you doing the operations?
  • Admin
    Admin almost 9 years
    3-(3*2) = 3-(6) = -3
  • aironman
    aironman about 7 years
    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
  • Peter Cordes
    Peter Cordes about 3 years
    What's the point of this? This is just a slow way to write n = -n, but with possible overflow in the n*2. Does that overflow do something useful? With n=-32768 we'd get n = +32768, which is outside the 2's complement -32768 .. +32767 range.