在Java中生成特定范围的随机双数 [英] Generating a random double number of a certain range in Java

查看:193
本文介绍了在Java中生成特定范围的随机双数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到的帖子几乎解释了这个问题,但他们都使用了整数值,老实说我不完全理解它因此这个问题:

I have seen posts which explains pretty much this question but they all used integer values and I honestly do not fully understand it hence this question:

我正在尝试在java中生成范围(-1554900.101)到(52952058699.3098)的随机数,我想知道是否有人可以向我解释这个,因为我真的想要理解它。

I am trying to generate random numbers from the range (-1554900.101) to (52952058699.3098) in java and I was wondering if anyone could explain this to me as I really want to understand it.

我的想法:
这是一个正确的方法吗?
1)在我指定的范围内生成一个随机整数
2)将生成的数字除以pi得到浮点数/双随机结果

My thoughts: will this be a right approach? 1) Generate a random integer number within my specified range 2) Divide the generated number by pi to get float/double random results

谢谢提前。

推荐答案

这是个主意。你想要一个范围内的随机数,假设 [ - 1.1,2.2] ,从一个简单的例子开始。该范围的长度为3.3,因为 2.2 - (-1.1)= 3.3 。现在,大多数随机函数返回 [0,1)范围内的数字,其长度为1,因此我们必须缩放我们的随机数数字到我们想要的范围。

Here's the idea. You want a random number in a range, let's say [-1.1,2.2], to start with a simple example. That range has length 3.3 since 2.2 - (-1.1) = 3.3. Now most "random" functions return a number in the range [0,1), which has length one, so we have to scale our random number into our desired range.

Random random = new Random();
double rand = random.nextDouble();
double scaled = rand * 3.3;

现在我们的随机数具有我们想要的幅度,但我们必须将它在数字线之间移位到我们想要的确切值。对于这一步,我们只需要将整个范围的下限添加到我们的缩放随机数中,我们就完成了!

Now our random number has the magnitude we want but we must shift it in the number line to be between the exact values we want. For this step, we just need to add the lower bound of the entire range to our scaled random number and we're done!

double shifted = scaled + (-1.1);

现在我们可以将这些部分放在一个函数中:

So now we can put these parts together in a single function:

protected static Random random = new Random();
public static double randomInRange(double min, double max) {
  double range = max - min;
  double scaled = random.nextDouble() * range;
  double shifted = scaled + min;
  return shifted; // == (rand.nextDouble() * (max-min)) + min;
}

当然,此函数需要对<$ c等意外值进行一些错误检查$ c> NaN 但是这个答案应该说明一般的想法。

Of course, this function needs some error checking for unexpected values like NaN but this answer should illustrate the general idea.

这篇关于在Java中生成特定范围的随机双数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆