Get random boolean in Java

JavaRandomBoolean

Java Problem Overview


Okay, I implemented this SO question to my code: https://stackoverflow.com/questions/8878015/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...

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

You could also try nextBoolean()-Method

Here is an example: http://www.tutorialspoint.com/java/util/random_nextboolean.htm

Solution 4 - Java

Java 8: Use random generator isolated to the current thread: ThreadLocalRandom nextBoolean()

> Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.

java.util.concurrent.ThreadLocalRandom.current().nextBoolean();

Solution 5 - Java

Why not use the Random class, which has a method nextBoolean:

import java.util.Random;

/** Generate 10 random booleans. */
public final class MyProgram {
  
  public static final void main(String... args){
    
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      boolean randomBool = randomGenerator.nextBoolean();
      System.out.println("Generated : " + randomBool);
    }
  }
}

Solution 6 - Java

You can use the following for an unbiased result:

Random random = new Random();
//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

Note: random.nextInt(2) means that the number 2 is the bound. the counting starts at 0. So we have 2 possible numbers (0 and 1) and hence the probability is 50%!

If you want to give more probability to your result to be true (or false) you can adjust the above as following!

Random random = new Random();

//For 50% chance of true
boolean chance50oftrue = (random.nextInt(2) == 0) ? true : false;

//For 25% chance of true
boolean chance25oftrue = (random.nextInt(4) == 0) ? true : false;

//For 40% chance of true
boolean chance40oftrue = (random.nextInt(5) < 2) ? true : false;

Solution 7 - Java

The easiest way to initialize a random number generator is to use the parameterless constructor, for example

Random generator = new Random();

However, in using this constructor you should recognize that algorithmic random number generators are not truly random, they are really algorithms that generate a fixed but random-looking sequence of numbers.

You can make it appear more 'random' by giving the Random constructor the 'seed' parameter, which you can dynamically built by for example using system time in milliseconds (which will always be different)

Solution 8 - Java

you could get your clock() value and check if it is odd or even. I dont know if it is %50 of true

And you can custom-create your random function:

static double  s=System.nanoTime();//in the instantiating of main applet
public static double randoom()
{
	
s=(double)(((555555555* s+ 444444)%100000)/(double)100000);

	
	return s;
}

numbers 55555.. and 444.. are the big numbers to get a wide range function please ignore that skype icon :D

Solution 9 - Java

You can also make two random integers and verify if they are the same, this gives you more control over the probabilities.

Random rand = new Random();

Declare a range to manage random probability. In this example, there is a 50% chance of being true.

int range = 2;

Generate 2 random integers.

int a = rand.nextInt(range);
int b = rand.nextInt(range);

Then simply compare return the value.

return a == b; 

I also have a class you can use. RandomRange.java

Solution 10 - Java

Words in a text are always a source of randomness. Given a certain word, nothing can be inferred about the next word. For each word, we can take the ASCII codes of its letters, add those codes to form a number. The parity of this number is a good candidate for a random boolean.

Possible drawbacks:

  1. this strategy is based upon using a text file as a source for the words. At some point, the end of the file will be reached. However, you can estimate how many times you are expected to call the randomBoolean() function from your app. If you will need to call it about 1 million times, then a text file with 1 million words will be enough. As a correction, you can use a stream of data from a live source like an online newspaper.

  2. using some statistical analysis of the common phrases and idioms in a language, one can estimate the next word in a phrase, given the first words of the phrase, with some degree of accuracy. But statistically, these cases are rare, when we can accuratelly predict the next word. So, in most cases, the next word is independent on the previous words.

    package p01;

    import java.io.File; import java.nio.file.Files; import java.nio.file.Paths;

    public class Main {

     String words[];
     int currentIndex=0;
    
     public static String readFileAsString()throws Exception 
       { 
         String data = ""; 
         File file = new File("the_comedy_of_errors");
         //System.out.println(file.exists());
         data = new String(Files.readAllBytes(Paths.get(file.getName()))); 
         return data; 
       } 
     
     public void init() throws Exception
     {
     	String data = readFileAsString(); 
     	words = data.split("\\t| |,|\\.|'|\\r|\\n|:");
     }
     
     public String getNextWord() throws Exception
     {
     	if(currentIndex>words.length-1)
     		throw new Exception("out of words; reached end of file");
     	
     	String currentWord = words[currentIndex];
     	currentIndex++;
     	
     	while(currentWord.isEmpty())
     	{
     		currentWord = words[currentIndex];
     		currentIndex++;
     	}
    
     	return currentWord;
     }
     
     public boolean getNextRandom() throws Exception
     {
     	String nextWord = getNextWord();
     	int asciiSum = 0;
     	
     	for (int i = 0; i < nextWord.length(); i++){
     	    char c = nextWord.charAt(i);        
     	    asciiSum = asciiSum + (int) c;
     	}
     	
     	System.out.println(nextWord+"-"+asciiSum);
     	
     	return (asciiSum%2==1) ;
     }
     
     public static void main(String args[]) throws Exception
     {
     	Main m = new Main();
     	m.init();
     	while(true)
     	{
     		System.out.println(m.getNextRandom());
     		Thread.sleep(100);
     	}
     }
    

    }

In Eclipse, in the root of my project, there is a file called 'the_comedy_of_errors' (no extension) - created with File> New > File , where I pasted some content from here: http://shakespeare.mit.edu/comedy_errors/comedy_errors.1.1.html

Solution 11 - Java

For a flexible boolean randomizer:

public static rbin(bias){
    bias = bias || 50;
    return(Math.random() * 100 <= bias);
    /*The bias argument is optional but will allow you to put some weight
      on the TRUE side. The higher the bias number, the more likely it is
      true.*/
}

Make sure to use numbers 0 - 100 or you might lower the bias and get more common false values.

PS: I do not know anything about Java other than it has a few features in common with JavaScript. I used my JavaScript knowledge plus my inferring power to construct this code. Expect my answer to not be functional. Y'all can edit this answer to fix any issues I am not aware of.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPavel JanicekView Question on Stackoverflow
Solution 1 - JavaaioobeView Answer on Stackoverflow
Solution 2 - JavaTheNewOneView Answer on Stackoverflow
Solution 3 - JavaSagiView Answer on Stackoverflow
Solution 4 - JavakinjelomView Answer on Stackoverflow
Solution 5 - JavafanfView Answer on Stackoverflow
Solution 6 - Javachristouandr7View Answer on Stackoverflow
Solution 7 - JavaPoeHaHView Answer on Stackoverflow
Solution 8 - Javahuseyin tugrul buyukisikView Answer on Stackoverflow
Solution 9 - JavaAngel FernandezView Answer on Stackoverflow
Solution 10 - Javawile the coyoteView Answer on Stackoverflow
Solution 11 - JavaMajor_Flux-View Answer on Stackoverflow