[java] 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...

This question is related to java random boolean

The answer is


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


You could also try nextBoolean()-Method

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


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

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


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;

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

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

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


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)


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas