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.
Asked
Active
Viewed 1.1e+01k times
38
-
This remind me about Rnd() of VB, it returns value in [0,1) only. – pinichi Oct 15 '10 at 02:36
-
1Possible 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 Answers
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
- 37,851
- 12
- 116
- 113
-
-
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
3
This is an old question I know but um....
n=n-(n*2)
-
-
1
-
-
1
-
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. – Peter Cordes Apr 23 '21 at 06:48
2
([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,993
- 1
- 18
- 14
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