__float2int_rn
has different behavior from the C style and C++ style casts. The C and C++ style cats will truncate, which means it just removes the floating point part of the number and gives you just the whole part. __float2int_rn
will
Convert a float to a signed integer in round-to-nearest-even mode.
and if we look up what round-to-nearest-even is from Wikipedia we have
A tie-breaking rule without positive/negative bias and without bias toward/away from zero is round half to even. By this convention, if the fractional part of x is 0.5, then y is the even integer nearest to x. Thus, for example, +23.5 becomes +24, as does +24.5; while −23.5 becomes −24, as does −24.5. This function minimizes the expected error when summing over rounded figures, even when the inputs are mostly positive or mostly negative.
This variant of the round-to-nearest method is also called convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd–even rounding,[6] or bankers' rounding.
This is the default rounding mode used in IEEE 754 operations for results in binary floating-point formats (see also nearest integer function), and the more sophisticated mode[clarification needed] used when rounding to significant figures.
By eliminating bias, repeated rounded addition or subtraction of independent numbers will give a result with an error that tends to grow in proportion to the square root of the number of operations rather than linearly. See random walk for more.
However, this rule distorts the distribution by increasing the probability of evens relative to odds. Typically this is less important than the biases that are eliminated by this method[citation needed].
So while
static_cast<int>(1.3f)
(int)1.3f
__float2int_rn(1.3f)
all produce the same results, with
static_cast<int>(23.5f)
(int)23.5f
__float2int_rn(23.5f)
the first two will evaluate to 23 while the __float2int_rn
call will result in 24.
__float2int_rn
variant, I suspect it does rounding of the value (based on thern
suffix). The other two methods truncate the value (i.e. just cut of the decimal part). Also, in C++ you really shouldn't do C-style casting, it should generally be seen as a sign that you're doing something wrong.