What does this line of code mean?

I am wondering what does this line of code mean?

b = (gen_rand_uniform()>0.5)?1:0;

gren_rand_uniform()is a function for generating random 0 and 1 numbers. However, I do not understand the meaning of >0.5and 1:0.

I know this should be the main question, please bear with me.

Thanks!

+3
source share
7 answers

This is a reduction. In the above example, this is equivalent to:

if (gen_rand_uniform() > 0.5) {
    b = 1;
} else {
    b = 0;
}

Since it gen_rand_uniform()probably generates evenly distributed random numbers between 1and 0, the probability of 50% is above 0.5. This means that there is a 50% chance of getting 1or0

+11
source

I do not think that get_rand_uniform()does what, in your opinion, does. It probably looks like this:

float get_rand_uniform(void);

, , double. , 0 1. , :

get_rand_uniform() > 0.5

, 1 0. :

x ? y : z

, , :

if(x) { y } else { z }

, . , :

get_rand_uniform() > 0.5 ? 1 : 0

1 0, :

b = get_rand_uniform() > 0.5 ? 1 : 0;

1 0 b. , , , .

+12

, 1 , 50% . "?" ":" .

+3

. b 0 1.

+3

. ( , .)

+1

:

variable = condition ? value_if_true : value_if_false;

:

if (condition) {
    variable = value_if_true;
} else {
    variable = value_if_false;
}

, , - bool. 1, 0.

0

, ternary expression. http://en.wikipedia.org/wiki/Ternary_operation ( ) , , , , .

( ., VB.Net)

condition ? valueiftrue: valueiffalse

:

var foo = true;
var bar = foo ? 'foo is true' : 'foo is false';
// bar = 'foo is true'

Also note that this condition can be any expression (for example, in your case gen_rand_uniform() > 0.5) and may contain an intract containing a nested ternary expression, all he needs to do is evaluate it as an invalid value.

0
source

Source: https://habr.com/ru/post/1720106/


All Articles