当一个浮点变量超出浮动范围,会发生什么? [英] When a float variable goes out of the float limits, what happens?

查看:384
本文介绍了当一个浮点变量超出浮动范围,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说两件事情:


  1. 的std :: numeric_limits<浮动> :: MAX()+(少量) 给出: 的std :: numeric_limits<浮动方式> :: MAX()


  2. 的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:

  1. std::numeric_limits<float>::max()+(a small number) gives: std::numeric_limits<float>::max().

  2. 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆