Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a random number with a negative number in range? [duplicate]

Tags:

java

random

Consider the following code:

int rand = new Random().nextInt((30 - 20) + 1) + 20

It will return a random number between 30 and 20. However, I need its range to include negative numbers. How would I include negative numbers in the generation?

I have tried using math that would be negative, but that resulted in an error. Simply subtracting or adding the negative numbers would not yield the desired value.


Sorry, I am only half awake. The correct code is int rand = new Random().nextInt((30 - 20) + 1) + 20;.

like image 474
CaffeineToCode Avatar asked Jan 16 '15 03:01

CaffeineToCode


People also ask

How do you make a random number negative in Excel?

Randomize negative integer numbers The formula =RANDBETWEEN(X,Y) also can insert negative integer numbers. (X and Y indicate any negative numbers, and X<Y), here, I type =RANDBETWEEN(-120,-20) into a blank cell and press Enter key, then if you need, you can drag the fill handle to fill a range.

Can range have negative numbers?

No. Because the range formula subtracts the lowest number from the highest number, the range is always zero or a positive number.

How do you randomize a negative number in Java?

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


2 Answers

To get a random number between a set range with min and max:

int number = random.nextInt(max - min) + min;

It also works with negative numbers.

So:

random.nextInt(30 + 10) - 10;
// max = 30; min = -10;

Will yield a random int between -10 and 30 (exclusive).

It also works with doubles.

like image 103
EDToaster Avatar answered Oct 14 '22 18:10

EDToaster


You can use Random.nextBoolean() to determine if it's a random positive or negative integer.

int MAX = 30;
Random random = new Random(); // Optionally, you can specify a seed, e.g. timestamp.
int rand = random.nextInt(MAX) * (random .nextBoolean() ? -1 : 1);
like image 42
KennyC Avatar answered Oct 14 '22 18:10

KennyC