What does it mean to assign Math.random () 0.5 to a variable?

4

What does this Math.random() > 0.5; mean in 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");
        }
    }
}
    
asked by anonymous 14.02.2016 / 22:48

3 answers

6

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

Soon your code snippet:

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

You are verifying that the value generated by the random function is greater than 0.5

If it is larger, true is set to that position in the array. Otherwise, arrow as false .

    
14.02.2016 / 22:53
5

It means exactly a 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 whether it is true or false. Then the response will be saved in the appropriate variable.

    
14.02.2016 / 22:54
5

The intent of the code author is that each vector element has a 50% chance to be true and 50% chance to be false .

In practice, this will not be entirely true for mathematical reasons, but it is 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 math expression, you can assign the result to a variable of the same type as the expression.

For example, the excerpt:

boolean var = Math.random() > 0.5;

Is the "summary" form of:

boolean var;
if (Math.random() > 0.5) {
    var = true;
} else {
    var = false;
}
    
15.02.2016 / 03:16