在范围内生成随机双精度

问题描述 投票:116回答:5

我有两个双打,如下所示

double min = 100;
double max = 101;

并且使用随机生成器,我需要在min和max的范围之间创建一个double值。

Random r = new Random();
r.nextDouble();

但这里没有任何东西我们可以指定范围。

java random
5个回答
208
投票

要在rangeMinrangeMax之间生成随机值:

Random r = new Random();
double randomValue = rangeMin + (rangeMax - rangeMin) * r.nextDouble();

115
投票

这个问题是在Java 7发布之前提出的,但是现在,还有另一种使用Java 7(及以上)API的方法:

double random = ThreadLocalRandom.current().nextDouble(min, max);

nextDouble将在最小值(包含)和最大值(不包括)之间返回伪随机双值。边界不一定是int,可以是double


37
投票

用这个:

double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));
System.out.println(result);

编辑:

new Random().nextDouble():随机生成0到1之间的数字。

start:开始编号,将数字“向右移”

end - start:间隔。 Random给出了这个数字的0%到100%,因为random给出了一个从0到1的数字。


编辑2:Tks @daniel和@aaa bbb。我的第一个答案是错的。


3
投票
import java.util.Random;
    public class MyClass {
         public static void main(String args[]) {
          Double min = 0.0; //  Set To Your Desired Min Value
          Double max = 10.0; //    Set To Your Desired Max Value
          double x = (Math.random() * ((max - min) + 1)) + min; //    This Will Create 
          A Random Number Inbetween Your Min And Max.
          double xrounded = Math.round(x * 100.0) / 100.0; // Creates Answer To 
          The Nearest 100 th, You Can Modify This To Change How It Rounds.
          System.out.println(xrounded); //    This Will Now Print Out The 
          Rounded, Random Number.
         }
    }

1
投票
Random random = new Random();
double percent = 10.0; //10.0%
if (random.nextDouble() * 100D < percent) {
    //do
}
© www.soinside.com 2019 - 2024. All rights reserved.