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
?
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
?
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.
return min + Math.random() * (max - min);