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
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.
It encodes a flip of the coin. (A perfectly balanced coin that is.)
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
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.
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.
It's rounding. The b variable will either be 0 or 1.