[英]When a float variable goes out of the float limits, what happens?
I remarked two things: 我说了两件事:
std::numeric_limits<float>::max()+(a small number)
gives: std::numeric_limits<float>::max()
. std::numeric_limits<float>::max()+(a small number)
给出: std::numeric_limits<float>::max()
。
std::numeric_limits<float>::max()+(a large number
like: std::numeric_limits<float>::max()/3)
gives inf. std::numeric_limits<float>::max()+(a large number
如: std::numeric_limits<float>::max()/3)
给出了 inf。
Why this difference? 为何如此区别? Does 1 or 2 results in an OVERFLOW and thus to an undefined behavior?
1或2会导致OVERFLOW导致未定义的行为吗?
Edit: Code for testing this: 编辑:测试此代码:
1. 1。
float d = std::numeric_limits<float>::max();
float q = d + 100;
cout << "q: " << q << endl;
2. 2。
float d = std::numeric_limits<float>::max();
float q = d + (d/3);
cout << "q: " << q << endl;
Formally, the behavior is undefined. 形式上,行为是不确定的。 On a machine with IEEE floating point, however, overflow after rounding will result in
Inf
. 但是, 在具有IEEE浮点的计算机上, 舍入后溢出将导致
Inf
。 The precision is limited, however, and the results after rounding of FLT_MAX + 1
are FLT_MAX
. 但是,精度是有限的,
FLT_MAX + 1
舍入后的结果是FLT_MAX
。
You can see the same effect with values well under FLT_MAX
. 在
FLT_MAX
下,您可以看到相同的效果。 Try something like: 尝试类似的东西:
float f1 = 1e20; // less than FLT_MAX
float f2 = f1 + 1.0;
if ( f1 == f2 ) ...
The if
will evaluate to true
, at least with IEEE arithmetic. if
将评估为true
,至少使用IEEE算法。 (There do exist, or at least have existed, machines where float
has enough precision for the if
to evaluate to false
, but they aren't very common today.) (确实存在,或者至少已经存在的机器,其中
float
具有足够的精度以便if
评估为false
,但它们在今天并不常见。)
It depends on what you are doing. 这取决于你在做什么。 If the float "overflow" comes in an expression which is directly returned, ie
如果float“overflow”出现在一个直接返回的表达式中,即
return std::numeric_limits::max() + std::numeric_limits::max();
the operation might not result in an overflow. 操作可能不会导致溢出。 I cite from the C standard [ISO/IEC 9899:2011]:
我引用C标准[ISO / IEC 9899:2011]:
The return statement is not an assignment.
return语句不是赋值。 The overlap restriction of subclause 6.5.16.1 does not apply to the case of function return.
子条款6.5.16.1的重叠限制不适用于函数返回的情况。 The representation of floating-point values may have wider range or precision than implied by the type;
浮点值的表示可以具有比类型所暗示的更宽的范围或精度; a cast may be used to remove this extra range and precision.
可以使用演员来消除这种额外的范围和精度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.