Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get random boolean in Java

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

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

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


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());       } } 

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

like image 909
Pavel Janicek Avatar asked Jul 13 '12 09:07

Pavel Janicek


People also ask

How do you generate a random number from 1 to 10 in Java?

For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);

Is there a random function in Java?

random() returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.


2 Answers

I recommend using Random.nextBoolean()

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) you're not working with the code you think you are, (like editing the wrong file)

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

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

like image 96
aioobe Avatar answered Oct 05 '22 19:10

aioobe


Have you tried looking at the Java Documentation?

Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence ... the values true and false are produced with (approximately) equal probability.

For example:

import java.util.Random;  Random random = new Random(); random.nextBoolean(); 
like image 44
TheNewOne Avatar answered Oct 05 '22 20:10

TheNewOne