当一个浮点变量超出浮动范围,会发生什么? [英] When a float variable goes out of the float limits, what happens?
问题描述
我说两件事情:
-
的std :: numeric_limits<浮动> :: MAX()+(少量)
给出:的std :: numeric_limits<浮动方式> :: MAX()
-
的std :: numeric_limits<浮动> :: MAX()+(大量
,如:的std :: numeric_limits<浮动&GT ; :: MAX()/ 3)
给 INF
为什么这种差异?请问1或2的结果溢出,从而未定义行为?
编辑: code测试这样的:
1
浮D =的std :: numeric_limits<浮球GT; :: MAX();
浮Q = D + 100;
COUT<< 问:<< Q<< ENDL;
2
浮D =的std :: numeric_limits<浮球GT; :: MAX();
浮Q = D +(D / 3);
COUT<< 问:<< Q<< ENDL;
在形式上,行为是不确定的。在与IEEE机器
浮点,但溢出的四舍五入后的会导致
在天道酬勤
。的precision是有限的,然而,结果的四舍五入后FLT_MAX + 1
是 FLT_MAX
。
您可以看到远低于 FLT_MAX
与价值观相同的效果。
尝试是这样的:
浮动F1 = 1E20; //小于FLT_MAX
漂浮F2 = F1 + 1.0;
如果(F1 == F2)...
的如果
将评估为真正
,至少对于IEEE运算。
(确实存在,至少已经存在,机器在哪里浮动
先后为如果
评估足够precision假
,但他们不是很常见的今天。)
I remarked two things:
std::numeric_limits<float>::max()+(a small number)
gives:std::numeric_limits<float>::max()
.std::numeric_limits<float>::max()+(a large number
like:std::numeric_limits<float>::max()/3)
gives inf.
Why this difference? Does 1 or 2 results in an OVERFLOW and thus to an undefined behavior?
Edit: Code for testing this:
1.
float d = std::numeric_limits<float>::max();
float q = d + 100;
cout << "q: " << q << endl;
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
. The precision is limited, however, and the results
after rounding of FLT_MAX + 1
are FLT_MAX
.
You can see the same effect with values well under 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.
(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.)
这篇关于当一个浮点变量超出浮动范围,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!