What does this line of code mean?

后端 未结 7 1018
抹茶落季
抹茶落季 2021-01-21 04:39

I am wondering what this line of code mean?

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

The gren_rand_uniform() is a function to generate

相关标签:
7条回答
  • 2021-01-21 05:06

    it's a way to get a random value which is either 1 or zero, each 50% of the time. The "?" and ":" are the conditional operarator.

    0 讨论(0)
  • 2021-01-21 05:07

    It encodes a flip of the coin. (A perfectly balanced coin that is.)

    0 讨论(0)
  • 2021-01-21 05:08

    It's shorthand. In the example you gave, it is equivalent to:

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

    Since gen_rand_uniform() probably generates uniformly distributed random numbers between 1 and 0, there's a 50% chance of the value being higher than 0.5. Which means there's a 50% chance of getting a 1 or a 0

    0 讨论(0)
  • 2021-01-21 05:09

    What you are seeing here is a ternary expression. http://en.wikipedia.org/wiki/Ternary_operation This is (as others here has pointed out) a conditional construct, but one that is specific to expressions, meaning that a value is returned.

    This construct exist in most languages (but not in eg. VB.Net) and has the form of

    condition ? valueiftrue: valueiffalse
    

    An example of this in action is:

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

    Also note that the condition can be any expression (like in your case gen_rand_uniform() > 0.5) and can infact contain a nested ternary expression, all it has to do is evaluate as a non-false value.

    0 讨论(0)
  • 2021-01-21 05:13

    I don't think get_rand_uniform() does what you think it does. It probably looks like this:

    float get_rand_uniform(void);
    

    Or maybe double. The point is, it returns a random decimal number between 0 and 1. So this:

    get_rand_uniform() > 0.5
    

    Is a check to see if that number is closer to 1 or 0. And this:

    x ? y : z
    

    Is the ternary conditional operator, which serves the same function as this:

    if(x) { y } else { z }
    

    Except that the ternary operator is an expression. So all of this:

    get_rand_uniform() > 0.5 ? 1 : 0
    

    Is basically rounding the random floating point number to 1 or 0, and this:

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

    Assigns that randomly picked 1 or 0 to b. I believe the parenthesis are unnecessary here, but if you like them, go for it.

    0 讨论(0)
  • 2021-01-21 05:21

    It's rounding. The b variable will either be 0 or 1.

    0 讨论(0)
提交回复
热议问题