当浮动变量超出浮动限制时,会发生什么?

When a float variable goes out of the float limits, what happens?(当浮动变量超出浮动限制时,会发生什么?)
本文介绍了当浮动变量超出浮动限制时,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说了两件事:

  1. std::numeric_limits<float>::max()+(一个小数) 给出: std::numeric_limits<float>::max().

std::numeric_limits<float>::max()+(a large number like: std::numeric_limits<float>::max()/3) 提供信息.

std::numeric_limits<float>::max()+(a large number like: std::numeric_limits<float>::max()/3) gives inf.

为什么会有这种差异?1 或 2 是否会导致 OVERFLOW 并因此导致未定义的行为?

Why this difference? Does 1 or 2 results in an OVERFLOW and thus to an undefined behavior?

测试代码:

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;

推荐答案

形式上,行为是未定义的.在具有 IEEE 的机器上然而,浮点数,四舍五入后会溢出在 Inf 中.但精度有限,结果FLT_MAX + 1 四舍五入后为 FLT_MAX.

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.

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 ) ...

if 将评估为 true,至少使用 IEEE 算法.(确实存在,或者至少曾经存在过这样的机器float 有足够的精度让 if 评估为false,但它们在今天并不常见.)

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.)

这篇关于当浮动变量超出浮动限制时,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)