Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

We all know (right?!) that one should not compare floating-point values by testing for equality (operator==).

But what if I actually want to determine whether two floats a and b are binary equal? If they're not allowed to be NaN (or other "special values"), is this "safe"? Can I rely on operator== to function in this way?

See Question&Answers more detail:os

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

1 Answer

(Assuming IEEE-754 representations) almost, but not quite. If you can rule out NaNs, you still need to deal with the fact that +0.0 and -0.0 have different binary encodings, but compare equal (because both are exactly zero).

Of course, C++ doesn't require IEEE-754. So strictly speaking, all bets are off.

If you want to check for (in)equality of encoding, just use memcmp(&a, &b, sizeof a).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...