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)
Author by
user455497
Updated on January 03, 2020Comments
-
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 over 10 yearsWhere are you using rand?
-
yoni almost 9 yearsLet'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 almost 9 yearsThis won't work. 3 = 3 - (3*2), 3 = -6.
-
Admin almost 9 yearsWrong. Order of operations.
-
GelatinFox almost 9 yearsNope, it still wont work. How are you doing the operations?
-
Admin almost 9 years3-(3*2) = 3-(6) = -3
-
aironman about 7 yearsscala> 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 about 3 yearsWhat's the point of this? This is just a slow way to write
n = -n
, but with possible overflow in then*2
. Does that overflow do something useful? Withn=-32768
we'd getn = +32768
, which is outside the 2's complement -32768 .. +32767 range.