0

I have seen MANY posts on here in regard to generating random numbers with a specific range in JAVA (especially this one). However, I have not found one that describes how to generate a random number between a negative MAX and a negative MIN. Is this possible in Java?

For example, if I want to generate a random number that is between (-20) and (-10). Using something like the below will only result in a JAVA Exception that screams about n having to be positive:

int magicNumber=(random.nextInt(-20)-10);
Community
  • 1
  • 1
Jonathan Scialpi
  • 771
  • 2
  • 11
  • 32
  • How about generating a *positive* random number between 10 and 20, and then taking the negative using `-`? I think it might work. – WhiteViking Sep 16 '15 at 21:30

3 Answers3

9

Just generate a random number between 10 and 20 and then negate it.

Amr
  • 792
  • 3
  • 15
  • That is more of a work around though rather than actually generating a random number. Don't you agree? – Jonathan Scialpi Sep 16 '15 at 21:09
  • 4
    @JonathanScialpi nope – m.antkowicz Sep 16 '15 at 21:11
  • 1
    Well I don't think that's a work around the definition of a random number is that each number is equally probable to be chosen right . So by this standard that is exactly what it does. Each number in your negative range is equally probable to be chosen so I think it makes sense to use it this way. – Amr Sep 16 '15 at 21:12
  • The community has spoken @Amr . Sounds like the answer to me... just to be clear, it is not possible to use any of the random java methods to produce a negative number right? This is due to the fact, that there must be a positive n? – Jonathan Scialpi Sep 16 '15 at 21:12
2

Another option would be to generate a random number between 0 and 10 and then subtract 20, if that feels less like a work-around to you.

gla3dr
  • 2,179
  • 16
  • 29
2

I'm not entirely sure what you want, but ThreadLocalRandom has a method which accepts a range, which can also have negative values:

ThreadLocalRandom.current().nextInt(-20, -10 + 1)

There is no practical difference to just negating the result of a positive random though.

Bubletan
  • 3,833
  • 6
  • 25
  • 33