IS"(浮点)==整数整数QUOT;保证在C#平等的吗? [英] Is "(float)integer == integer" guaranteed to be equal in C#?
问题描述
虽然大家都知道 X ==是
可能会有问题,其中 X
和是
的浮点值,这个问题是一个比较具体的:
INT点¯x = random.Next(SOME_UPPER_LIMIT);
浮动R = X;
//是企业始终以下是真的吗?
R ==点¯x
现在,因为范围的浮动的比整数更大(但精度不够唯一在边缘目前整数),它将如果对这个问题回答的也的讨论的哪些值是不错X
上面可以保证,如果它能够在所有的保证。
目前我的代码的是的使这个假设(对x的值相对较小) - 我想确保我不会被咬:)
< HR>
这将失败,并不等于:16777217(投浮法 - > INT):
的for(int i = 0; I< int.MaxValue;我++){
浮动F = I;
如果(!(INT)F = I)抛出新的异常(不等于+ I);
}
这类似的代码不会失败(仅INT - >浮动);然而,由于在转换损失,有几种浮子,可以等于相同的整数的,并且可以代表一个无声的错误:
的for(int i = 0; I< int.MaxValue;我++){
浮动F = I;
如果(!F = I)抛出新的异常(不等于+ I);
}
是的,比较总会是真实的,任何值 INT
是
的
INT
将被转换为一个浮动
做转换,第一次转换到浮动
总是给出相同的。结果作为第二次转换
考虑:
INT X = [任意整数]。
浮动Y = X;
浮动Z = X;
是
和<$ C的值$ C>以Z 将永远是相同的。如果转换损失精度,既转换会失去精度完全相同的方式。
如果您转换浮动
回 INT
来的比较,那是另一回事了。
此外,请注意,即使一个特定的 INT
值转换为浮动
结果总是在同一个浮动
价值,这并不意味着浮动
值必须为 INT $独一无二C $ C>值。有
INT
值,其中(浮点)x ==(浮点)(X + 1)
是真正
。
While "we all know" that x == y
can be problematic, where x
and y
are floating point values, this question is a bit more specific:
int x = random.Next(SOME_UPPER_LIMIT);
float r = x;
// Is the following ALWAYS true?
r == x
Now, since the range of float of is much larger than that of integers (but the precision is insufficient to uniquely present integers at the edges), it would be nice if responses to this question also addressed which values of x
the above can be guaranteed for, if it can be guaranteed at all.
Currently my code is making this assumption (for relatively small values of x) - I would like to make sure that I won't get bitten :)
This will fail with "not equal: 16777217" (cast float -> int):
for (int i = 0; i < int.MaxValue; i++) {
float f = i;
if ((int)f != i) throw new Exception("not equal " + i);
}
This similar code will not fail (only int -> float); however, due to loss in the conversion, there are several floats that can "equal" the same integer, and may represent a silent bug:
for (int i = 0; i < int.MaxValue; i++) {
float f = i;
if (f != i) throw new Exception("not equal " + i);
}
Yes, the comparison will always be true, whatever value the int
is.
The int
will be converted to a float
to do the conversion, and the first conversion to float
will always give the same result as the second conversion.
Consider:
int x = [any integer value];
float y = x;
float z = x;
The values of y
and z
will always be the same. If the conversion loses precision, both conversions will lose the precision in exactly the same way.
If you convert the float
back to int
to to the comparison, that's another matter.
Also, note that even if a specific int
value converted to float
always results in the same float
value, that doesn't mean that the float
value has to be unique for that int
value. There are int
values where (float)x == (float)(x+1)
would be true
.
这篇关于IS"(浮点)==整数整数QUOT;保证在C#平等的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!