-1

I'm trying to figure out how to best generate a random number between -1 and 1. I thought this was the formula below but my output is always 0s and 1s, no negatives.

random.nextInt(max + 1 - min) + min

Here's the actual code:

int xRand = random.nextInt((1 + 1 + 1) - 1);
int yRand = random.nextInt((1 + 1 + 1) - 1);

System.out.println("x: " + xRand);
System.out.println("y: " + yRand);
jww
  • 97,681
  • 90
  • 411
  • 885
Nick Green
  • 101
  • 1
  • 9
  • "`random.nextInt(max + 1 - min) + min`" Note that isn't what you've got in the code. (Perhaps it would be clearer if you created variables `min` and `max`) – Andy Turner Jan 02 '19 at 16:49
  • 1
    Your formula is correct, but you're not applying it at all. max is 1, min is -1, so it should be `random.nextInt(1 + 1 - (-1)) + (-1)`, or `random.nextInt(3) - 1`. You're using `random.nextInt(2)` – JB Nizet Jan 02 '19 at 16:49
  • 1
    Possible duplicate of [How to generate random integers within a specific range in Java?](https://stackoverflow.com/q/363681/608639), [How to generate random positive and negative numbers in Java](https://stackoverflow.com/q/363681/608639), etc. More generally, [java generate random number in range site:stackoverflow.com](https://www.google.com/search?q=java+generate+random+number+in+range+site%3Astackoverflow.com) – jww Jan 02 '19 at 17:55

2 Answers2

2

You state in the question

random.nextInt(max + 1 - min) + min

But, using max == 1 and min == -1, you have written

random.nextInt((max + 1 - min) + min)

Move the final -1 out of the brackets.

int xRand = random.nextInt(1 + 1 + 1) - 1;

(And consider using variables named min and max instead of magic numbers that you won't know the meaning of when you come back to this code later).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
-1

random.nextInt(1 + 1 + 1) - 1

random.nextInt(1 + 1 + 1) will generate a random integer from 0 to 2 (think of mod 3)

Adding -1 will then result in it generating from -1 to 1

Arne
  • 1,293
  • 1
  • 7
  • 20