Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is floating-point == ever OK?

Just today I came across third-party software we're using and in their sample code there was something along these lines:

// Defined in somewhere.h static const double BAR = 3.14;  // Code elsewhere.cpp void foo(double d) {     if (d == BAR)         ... } 

I'm aware of the problem with floating-points and their representation, but it made me wonder if there are cases where float == float would be fine? I'm not asking for when it could work, but when it makes sense and works.

Also, what about a call like foo(BAR)? Will this always compare equal as they both use the same static const BAR?

like image 697
murrekatt Avatar asked Jan 13 '11 17:01

murrekatt


People also ask

Why do we never use == to compare floating point numbers?

Because floating point arithmetic is different from real number arithmetic. Bottom line: Never use == to compare two floating point numbers. Here's a simple example: double x = 1.0 / 10.0; double y = x * 10.0; if (y !=

Are floating point comparisons reliable?

The floating point comparison is not similar to the integer comparison. To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

Why is floating point not accurate?

Floating-point decimal values generally do not have an exact binary representation. This is a side effect of how the CPU represents floating point data. For this reason, you may experience some loss of precision, and some floating-point operations may produce unexpected results.

What is a valid floating point value?

64-bit signed floating point number. A signed floating point number. Either a decimal point (.) or an exponent symbol (e) must be present within the number for it to be a valid float.


1 Answers

Yes, you are guaranteed that whole numbers, including 0.0, compare with ==

Of course you have to be a little careful with how you got the whole number in the first place, assignment is safe but the result of any calculation is suspect

ps there are a set of real numbers that do have a perfect reproduction as a float (think of 1/2, 1/4 1/8 etc) but you probably don't know in advance that you have one of these.

Just to clarify. It is guaranteed by IEEE 754 that float representions of integers (whole numbers) within range, are exact.

float a=1.0; float b=1.0; a==b  // true 

But you have to be careful how you get the whole numbers

float a=1.0/3.0; a*3.0 == 1.0  // not true !! 
like image 54
Martin Beckett Avatar answered Oct 15 '22 21:10

Martin Beckett