How do you get random Double
values between 0.0 and 0.06 in Java?
views:
150answers:
5
+7
A:
This will give you a random double in the interval [0,0.06):
double r = Math.random()*0.06;
uckelman
2010-02-09 16:52:51
+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
2010-02-09 16:53:04
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
2010-02-09 19:58:11
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
2010-05-13 19:42:28
@Fakrudeen, wow, indeed. number = Math.min(number, 0.06);
Justin
2010-05-13 19:50:46
+1
A:
Based on this java doc (though watch the boundary condition):
new Random().nextDouble() * 0.06
Michael Easter
2010-02-09 16:56:36
+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
2010-05-13 20:53:51