Which means assign Math.random ()> 0.5 to a variable?

What Does Math.random() > 0.5; mean in a boolean? Here is an example:

class Pro {

    public static void main(String[] args) {

        int numero = 10;
        boolean[] array = new boolean[numero];
        for(int i= 0; i< array.length; i++) {
           array[i] = Math.random() > 0.5;
           System.out.print(array[i] + "\t");
        }
    }
}
Author: Maniero, 2016-02-14

3 answers

Math.random() will generate a value between 0 and 0.999999(tends to the limit of 1, but does not reach 1).

Soon your code snippet:

array[i] = Math.random() > 0.5;

Is checking if the value generated by the function random is greater than 0.5

If larger, true is set to that array position. Otherwise, Arrow as false.

 7
Author: Weslley Tavares, 2016-02-14 21:53:35

The intention of the author of the code is that each element of the Vector has a 50% chance of being true and a 50% chance of being false.

In practice, this isn't going to be totally true for mathematical reasons, but it's close enough.

As for the Code, Math.random() > 0.5 is a expression that returns a boolean value, that is, true or false.

As with any mathematical expression, you can assign the result to a variable of the same type generated by the expression.

For example, the snippet:

boolean var = Math.random() > 0.5;

Is the "summary" form of:

boolean var;
if (Math.random() > 0.5) {
    var = true;
} else {
    var = false;
}
 6
Author: utluiz, 2016-02-15 03:00:07

Means exactly one boolean. What is the response of the expression Math.random() > 0.5? It will be true or false, right? It will check if the number drawn is greater than half and get the result if it is true or false, then the answer will be saved in the appropriate variable.

 5
Author: Maniero, 2019-12-03 15:17:03