java java中介于0.0和1.0之间的随机浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10536189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:28:38  来源:igfitidea点击:

Random float between 0.0 and 1.0 both inclusive in java

javarandom

提问by rickbear

Possible Duplicate:
Random floating point double in Inclusive Range

可能的重复:
包含范围内的随机浮点双精度

I'm working on a project where I need the random float between 0.0 and 1.0 both inclusive. After considering a while I found out that it's propably not that important for my project anyway, so I just use the standard:

我正在做一个项目,我需要在 0.0 和 1.0 之间的随机浮点数。考虑了一段时间后,我发现无论如何它对我的项目来说可能并不那么重要,所以我只使用标准:

new Random().nextFloat();

which generates a float from 0.0 (inlcusive) to 1.0 (exclusive).

它生成从 0.0(包含)到 1.0(不包含)的浮点数。

But I can't stop thinking how it's actually accomplished to make with 1.0 inclusive?

但我不能停止思考它是如何用 1.0 inclusive 完成的?

One method I could think of is (pseudocode):

我能想到的一种方法是(伪代码):

new Random().nextFloat() * (1.0 + "lowest possible value above 0");

Another method I could think of is:

我能想到的另一种方法是:

float myRandomFloat = 0;
float rand1 = new Random().nextFloat(); // [0;1)
float rand2 = 1.0f - new Random().nextFloat(); // (0;1]
boolean randPicker = new Random().nextBoolean();
if (randPicker)
    myRandomFloat = rand1;
else
    myRandomFloat = rand2;

But I think this ought to be more simple or not? So my real question is: Is there a real or better way of doing this?

但我认为这应该更简单吗?所以我真正的问题是:有没有真正的或更好的方法来做到这一点?

回答by Euclides Mulémbwè

if you multiply Random().nextFloat() by 10 it will give you a number from 0 to 9 which are the base numbers in the numeral system, so number 10 doesn't really exist but it's a combination of two base numbers, so you will never be able to get it as a random number, but if you really need it I would go with your second option.

如果你将 Random().nextFloat() 乘以 10,它会给你一个从 0 到 9 的数字,这是数字系统中的基数,所以数字 10 并不真正存在,但它是两个基数的组合,所以您将永远无法将其作为随机数获取,但如果您真的需要它,我会选择您的第二个选项。