search

Home  >  Q&A  >  body text

java 生成随机数

Random 类的实例 random

random.doubles(1, var1, var2  ).findFirst().orElse(0);

貌似只能生成 [var1, var2) 的随机数(左闭右开),
我想生成[var1, var2](左闭右闭)的该怎么写?

迷茫迷茫2805 days ago823

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-18 09:51:20

    Solution:
    random.doubles(1, var1, var2 + Double.MIN_VALUE).findFirst().orElse(0);

    Double can represent too many decimal places, so in terms of probability, the chance of randomly generating var2 is too small, so the author is advised to ignore it. If you only take a fixed number of decimal places, such as 2 decimal places, you can do this:

    // 取[1.20, 1.30]
    long n = random.longs(1, 120, 130 + 1).findFirst().orElse(0);
    // 将n的小数点左移两位

    reply
    0
  • Cancelreply