Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random positive and negative numbers in Java [duplicate]

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.

like image 449
user455497 Avatar asked Oct 15 '10 02:10

user455497


People also ask

How do you randomize a negative number in Java?

The correct code is int rand = new Random(). nextInt((30 - 20) + 1) + 20; .

How do you generate random positive numbers in Java?

The nextDouble() and nextFloat() method generates random value between 0.0 and 1.0. The nextInt(int bound) method accepts a parameter bound (upper) that must be positive. It generates a random number in the range 0 to bound-1.

How do you generate a double random value in Java?

In order to generate Random double type numbers in Java, we use the nextDouble() method of the java. util. Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.

How do you generate a 15 digit unique random number in Java?

Random random = new Random(); int rand15Digt = random. nextInt(15);


3 Answers

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

like image 96
pinichi Avatar answered Oct 02 '22 08:10

pinichi


Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);
like image 24
Truth Avatar answered Oct 02 '22 07:10

Truth


public static int generatRandomPositiveNegitiveValue(int max , int min) {
    //Random rand = new Random();
    int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
    return ii;
}
like image 6
duggu Avatar answered Oct 02 '22 06:10

duggu