在Java中获取随机布尔值

2022-01-19 00:00:00 random boolean java

好的,我在我的代码中实现了这个 SO 问题:随机返回真或假

Okay, I implemented this SO question to my code: Return True or False Randomly

但是,我有一个奇怪的行为:我需要同时运行十个实例,每个实例每次运行只返回一次 true 或 false.令人惊讶的是,无论我做什么,每次我得到的只是 false

But, I have strange behavior: I need to run ten instances simultaneously, where every instance returns true or false just once per run. And surprisingly, no matter what I do, every time i get just false

有什么可以改进的方法,所以我至少有大约 50% 的机会获得 true?

Is there something to improve the method so I can have at least roughly 50% chance to get true?

为了更容易理解:我将我的应用程序构建为 JAR 文件,然后通过批处理命令运行

To make it more understandable: I have my application builded to JAR file which is then run via batch command

 java -jar my-program.jar
 pause

程序的内容 - 使其尽可能简单:

Content of the program - to make it as simple as possible:

public class myProgram{

    public static boolean getRandomBoolean() {
        return Math.random() < 0.5;
        // I tried another approaches here, still the same result
    }

    public static void main(String[] args) {
        System.out.println(getRandomBoolean());  
    }
}

如果我打开 10 个命令行并运行它,我每次都会得到 false 作为结果...

If I open 10 command lines and run it, I get false as result every time...

推荐答案

我推荐使用 Random.nextBoolean()

话虽如此,Math.random() <0.5 您也使用过作品.这是我机器上的行为:

That being said, Math.random() < 0.5 as you have used works too. Here's the behavior on my machine:

$ cat myProgram.java 
public class myProgram{

   public static boolean getRandomBoolean() {
       return Math.random() < 0.5;
       //I tried another approaches here, still the same result
   }

   public static void main(String[] args) {
       System.out.println(getRandomBoolean());  
   }
}

$ javac myProgram.java
$ java myProgram ; java myProgram; java myProgram; java myProgram
true
false
false
true

不用说,无法保证每次都能获得不同的值.然而,在你的情况下,我怀疑

Needless to say, there are no guarantees for getting different values each time. In your case however, I suspect that

A)您没有使用您认为的代码,(例如编辑错误的文件)

A) you're not working with the code you think you are, (like editing the wrong file)

B) 你在测试时没有编译你的不同尝试,或者

B) you havn't compiled your different attempts when testing, or

C) 您正在使用一些非标准的损坏实现.

C) you're working with some non-standard broken implementation.

相关文章