在 Java 中获取 0 到 0.06 之间的随机数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2230814/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:10:58  来源:igfitidea点击:

Getting a random number between 0 and 0.06 in Java?

javarandom

提问by podunk

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

你如何Double在 Java 中获得0.0 和 0.06 之间的随机值?

回答by Dolph

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

nextDouble()返回一个在 0 和 1 之间均匀分布的随机浮点数。只需按如下方式缩放结果:

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

See this documentationfor more examples of Random.

有关Random 的更多示例,请参阅此文档

回答by uckelman

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

这将为您提供区间 [0,0.06) 中的随机双倍:

double r = Math.random()*0.06;

回答by Peter Lawrey

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)

为避免浮点值的不精确性,您可以使用更准确的双精度/整数计算(至少在 x86/x64 平台上)

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

回答by chburd

you need to have a look at the Randomclass

你需要看看Random

回答by Michael Easter

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

基于这个java doc(虽然看边界条件):

 new Random().nextDouble() * 0.06