首页 文章

在范围内生成随机双精度

提问于
浏览
113

我有两个双打,如下所示

double min = 100;
double max = 101;

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

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

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

6 回答

  • 0

    要生成 rangeMinrangeMax 之间的随机值:

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

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

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

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

  • 198

    用这个:

    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() :随机生成0到1之间的数字 .

    start :开始编号,换班号"to the right"

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


    EDIT 2: Tks @daniel和@aaa bbb . 我的第一个答案是错的 .

  • 35
    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.
             }
        }
    
  • 3
    Random random = new Random();
    double percent = 10.0; //10.0%
    if (random.nextDouble() * 100D < percent) {
        //do
    }
    
  • -1

    double var1 = LowerLimit new Random() . nextDouble()*(UpperLimit - LowerLimit); System.out.println(“\ n \ nRandom范围内的两倍是:”var1);

相关问题