生成不包括下限的随机数

huangapple go评论78阅读模式
英文:

generating random number with lower bound excluded

问题

我想在 x 和 y 之间生成一个满足条件 (x, y] 的随机数。

我正在使用 Java。

我知道要排除上界,可以使用 Math.random() * y,但是对于下界该如何处理呢?我不确定这种方法该怎么做,因为 Math.random 函数返回的是相反的区间 [0, 1),所以我不确定如何进行反转。

我还查看了这个来源以寻找答案,但是没有找到合适的解决方法。
https://careerkarma.com/blog/java-math-random/#:~:text=The%20Math.,is%20always%20less%20than%201

请告诉我。

英文:

I would like to generate a random number between x and y with the conditions (x, y] so x is excluded but y is included.

I am using Java.

I know that for the upper bound to be excluded it is Math.random * y but what do you do for lower bound? I am not sure how you would do it this way because the Math.random function returns the opposite [0, 1) so I am not sure how you would inverse that.

I also took a link at this source for answers but I didn't get any luck.
https://careerkarma.com/blog/java-math-random/#:~:text=The%20Math.,is%20always%20less%20than%201.

Please let me know

答案1

得分: 1

获取 (0, 1] 区间的随机数,你可以使用 1.0 - Math.random()

double randomDouble = 1.0 - Math.random();

然后你可以像平常一样获取任意范围的随机数。例如,如果你想要位于 (6, 10] 区间的任意双精度数,你可以这样做:

double randomDouble = (1.0 - Math.random()) * (10.0 - 6.0) + 6.0;

或者使用通用的方式:

double randomDouble = (1.0 - Math.random()) * (max - min) + min;
英文:

To get (0, 1], you can just take 1.0 - Math.random()

double randomDouble = 1.0 - Math.random();

From that you can just do the normal things to get between a random. For example, if you want any double that is (6, 10], you can just do this:

double randomDouble = (1.0 - Math.random()) * (10.0 - 6.0) + 6.0;

Or just the generic

double randomDouble = (1.0 - Math.random()) * (max - min) + min;

答案2

得分: 0

> 规则: 如果 a[x,y[​ 中,则 a+1]x,y]​ 中。


因此,已知的公式是 double r = Math.random() * (upp - low) + low;

因此,使用 +1,它变为

Random rand = new Random()
int low = 10,upp = 20;

// 对于 double
double r = 1 + rand.nextDouble() * (upp - low) + low;

// 对于 int
int r = 1 + rand.nextInt(upp - low) + low;
英文:

> Rule: If a is in [x, y[ then a+1 is in ]x,y]


So the known formula is double r = Math.random() * (upp - low) + low;

So, using the +1, it becomes

Random rand = new Random()
int low = 10, upp = 20;

// for a double
double r = 1 + rand.nextDouble() * (upp - low) + low;

// for an int
int r = 1 + rand.nextInt(upp - low) + low;

huangapple
  • 本文由 发表于 2020年10月25日 05:08:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/64518018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定