tags:

views:

150

answers:

5

How do you get random Double values between 0.0 and 0.06 in Java?

+1  A: 

you need to have a look at the Random class

chburd
+7  A: 

This will give you a random double in the interval [0,0.06):

double r = Math.random()*0.06;
uckelman
+10  A: 

nextDouble() returns a random floating-point number uniformly distributed between 0 and 1. Simply scale the result as follows:

Random generator = new Random();
double number = generator.nextDouble() * .06;

See this documentation for more examples of Random.

Dolph
Also you may have to check that number is less than < 0.06, floating point operations are not exact [in the sense there is always some error/uncertainty which accumulates over many floating point operations].
Fakrudeen
Also beware of using a new instance of `Random` for every number you need. In that sense, uckelman's answer below is better as it specifically avoids that common mistake.
Joey
@Fakrudeen, wow, indeed. number = Math.min(number, 0.06);
Justin
+1  A: 

Based on this java doc (though watch the boundary condition):

 new Random().nextDouble() * 0.06
Michael Easter
+1  A: 

To avoid the inexactness of floating point values you can use a double/integer calculation which is more accurate (at least on x86/x64 platforms)

double d = Math.random() * 6 / 100;
Peter Lawrey