-1
        double random1 = Math.random() * 9 + -9;
        double random2 = Math.random() * -9 + 9;

I need randomly generated numbers ranging from -9 to 9 using Math.random. When I use this code I have here it only prints the first number as a negative number.I've ran this multiple times and still the first number is always negative while the second is positive. How can I fix this to be more random? Thanks

  • 1
    determine the length of result space (from `-9` to `9`), multiply the random value by this length, subtract the lower bound of the result space. – Turing85 Apr 07 '18 at 19:14
  • 2
    While asking questions you should get list of potentially related questions. One of them should be [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/q/363681) (taken from list called `Related` at right side of this page). Did you visit it? – Pshemo Apr 07 '18 at 19:15
  • Always **search Stack Overflow** before posting. – Basil Bourque May 07 '19 at 04:25

3 Answers3

2

Math.random() generates a number between 0 and 1.

How about multiplying by 18 and then subtracting 9?

camickr
  • 321,443
  • 19
  • 166
  • 288
1

From jdk-7 you can use ThreadLocalRandom

public int nextInt(int origin, int bound)

Returns a pseudorandom int value between the specified origin (inclusive) and the specified bound (exclusive).

ThreadLocalRandom.current().nextInt(-9, 10) // will generate from -9>=x<10
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
0

When you want a value between a number min and a number max :

Math.random() * ((max - min) + 1) + min
Sébastien S.
  • 1,444
  • 8
  • 14