[英]Java Random double in interval [-1000, 1000]
In java I have:在java中我有:
Random random = new Random();
double randomNum = random.nextDouble();
which creates a random number between 0 and 1. However I want a number between -1000 and 1000, how would I scale this?它创建了一个介于 0 和 1 之间的随机数。但是我想要一个介于 -1000 和 1000 之间的数字,我该如何缩放呢?
Thanks谢谢
2 possibilities: 2种可能性:
Note that possibility 2 ensures better randomness and better 'density' of your numbers, at the cost of 2 random calls [which might be expansive, if it is an issue]. 请注意,可能性2确保了更好的随机性和更好的“密度”,以2次随机调用为代价[如果这是一个问题,这可能是扩展性的]。
嗯,数学?
double randomNum = (random.nextDouble()-0.5d) * 2000;
Random random = new Random();
double randomNum = (random.nextDouble() * 2000.0d) - 1000.0d;
public static double randomInterval(double minValue,double maxValue){
Random random = new Random();
double r;
do {
r = random.nextDouble();
} while (r < minValue || r >= maxValue);
return r;
}
double a = randomInterval(-1000,1000) ;
Try this algorithm: 试试这个算法:
这会为您提供该范围内的数字
double randomNum = (random.nextDouble() * 2000) -1000;
Random random = new Random();
int randomNum = random.nextInt(2000) - 1000;
Here is a general function you could use to linearly rescale a number between zero and one ( val01
) to a different range ( min
.. max
): 这是一个通用函数,您可以使用val01
零到一( val01
)之间的数字线性重新缩放到不同的范围( min
.. max
):
public static double rescale(double val01, double min, double max) {
return val01 * (max - min) + min;
}
public static double doubleBetween(double start, double end) {
Random random = new Random();
// We need 64 bits because double have 53 bits precision, so int is too short
// We have now a value between 0 and Long.MAX_VALUE.
long value = -1L;
while (value < 0)
value = Math.abs(random.nextLong()); // Caution, Long.MIN_VALUE returns negative !
// Cast to double
double valueAsDouble = (double) value;
// Scale so that Long.MAX_VALUE is exactly 1 !
double diff = (end-start)/(double) Long.MAX_VALUE;
return start + valueAsDouble*diff;
}
This will give the correct interval including both ends with full double precision. 这将给出正确的间隔,包括两端的全双精度。 doubles have a special -0.0 value (the negative zero) which will not be given by this routine. 双精度具有一个特殊的-0.0值(负零),该程序不会给出该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.