3

Possible Duplicate:
Generating random number in a range with Java

double x = //Random number between -0.5 and 0.5

Possible Outputs:

-0.23
0.01
0.26
-0.4

How do I generate a double between the range of (example) -0.5 and 0.5?

Community
  • 1
  • 1
user1621988
  • 4,215
  • 8
  • 27
  • 31

2 Answers2

20
return min + Math.random() * (max - min);
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
6

This should do it

Math.random() - 0.5

Math.random will generate betweeen 0 and 1. If you want between -0.5 and +0.5 then you can just -0.5 from this result. See the API docs

One thing that this will not do is ever give you 0.5 as Math.random() does never return 1. This post will give you more details and a possible solution.

Community
  • 1
  • 1
RNJ
  • 15,272
  • 18
  • 86
  • 131
  • Thanks all, but this was the easiest one for what I needed :) – user1621988 Sep 12 '12 at 19:46
  • @Baz okay thanks for explaination. So it cant return 0.5 or -0.5. Anyways it's not a big deal in my case. Thanks! – user1621988 Sep 12 '12 at 19:50
  • 1
    @user1621988 You should thank RNJ, since he posted this answer. To be exact: it **can** result in `-0.5`, it **cannot** result in `0.5`. – Baz Sep 12 '12 at 19:52