java 在 [0,1] 和限制小数之间生成浮点随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33437868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate float Random number between [0,1] and restricting decimal
提问by Shubham agarwal
I want to generate Random Float numbers between Interval [0,1]. The generated Random values will be compared with an input from a file. The content of the File is a probability (float values) and hence they are in range[0,1] and it looks like:
我想在区间 [0,1] 之间生成随机浮点数。生成的随机值将与来自文件的输入进行比较。文件的内容是一个概率(浮点值),因此它们在 [0,1] 范围内,看起来像:
0.55
0.55
0.14
0.14
0.005
0.005
0.870
0.870
0.98
0.98
0
0
1
1
I am reading this File and storing probability values into a DoubleList. Now I want to generate a float Random Number between [0,1]. As you see the file have probability values upto 1 digit, 2 digits decimal and 3 digits decimal as well. I am using following Code:
我正在阅读此文件并将概率值存储到DoubleList 中。现在我想在 [0,1] 之间生成一个浮点随机数。如您所见,该文件具有最多 1 位、2 位小数和 3 位小数的概率值。我正在使用以下代码:
public static double randomNumberGenerator()
{
double rangeMin = 0.0f;
double rangeMax = 1.0f;
Random r = new Random();
double createdRanNum = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
return(createdRanNum);
}
The random float value generated should be also be like Probabilities values (like generated upto the maximal decimal digits as in the file). How can I restrict the generated decimal digits?
生成的随机浮点值也应该像概率值一样(就像在文件中生成的最大十进制数字一样)。如何限制生成的十进制数字?
I checked the following Link: Java random number between 0 and 0.06. People suggested Int number generation and then did the double division by 100. Is this the good way? Can't we restrict the decimal generated directly?
我检查了以下链接:Java random number between 0 and 0.06。人们建议生成整数,然后再除以 100。这是好方法吗?不能限制直接生成的小数吗?
PS: If I compare the random generated number from the above code with the double values from File, would there be some memory fall issues in the DoubleList?
PS:如果我将上面代码中随机生成的数字与 File 中的双精度值进行比较,DoubleList 中是否会出现一些内存下降问题?
回答by aleroot
You could just use Java Randomclass :
你可以只使用 Java Random类:
Random rand = new Random();
rand.nextFloat()
which returns the random float number between 0.0f (inclusive) and 1.0f(exclusive).
它返回 0.0f(含)和 1.0f(不含)之间的随机浮点数。
To round the result of the nextFloat()
you could just use an helper method like the following :
要舍入结果,nextFloat()
您可以使用如下所示的辅助方法:
public static float round(float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.floatValue();
}