英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论