Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

c++ - When a float variable goes out of the float limits, what happens?

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...