Generate a random double in a range
I have two doubles like the following
double min = 100;
double max = 101;
and with a random generator, I need to create a double value between the range of min and max.
Random r = new Random();
r.nextDouble();
but there is nothing here where we can specify the range.
要在rangeMin和rangeMax之间生成一个随机值:
Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
This question was asked before Java 7 release but now, there is another possible way using Java 7 (and above) API:
double random = ThreadLocalRandom.current().nextDouble(min, max);
nextDouble will return a pseudorandom double value between the minimum (inclusive) and the maximum (exclusive). The bounds are not necessarily int , and can be double .
Use this:
double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));
System.out.println(result);
EDIT:
new Random().nextDouble() : randomly generates a number between 0 and 1.
start : start number, to shift number "to the right"
end - start : interval. Random gives you from 0% to 100% of this number, because random gives you a number from 0 to 1.
EDIT 2: Tks @daniel and @aaa bbb. My first answer was wrong.
链接地址: http://www.djcxy.com/p/17730.html上一篇: 获得Flash CS4 Intelisense在舞台上识别对象?
下一篇: 在一个范围内生成一个随机double
