Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange output in comparison of float with float literal

float f = 0.7; if( f == 0.7 )     printf("equal"); else     printf("not equal"); 

Why is the output not equal ?

Why does this happen?

like image 548
Ashish Avatar asked Dec 03 '09 11:12

Ashish


People also ask

What is a better way to compare floating point values?

To compare two floating point or double 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 it a problem to compare two floating point numbers?

In the case of floating-point numbers, the relational operator (==) does not produce correct output, this is due to the internal precision errors in rounding up floating-point numbers. In the above example, we can see the inaccuracy in comparing two floating-point numbers using “==” operator.

What happens if we compare int with float in C?

Casting the int to a float explicitly will do absolutely nothing. The int will be promoted to a float for purposes of comparison anyway.


2 Answers

This happens because in your statement

  if(f == 0.7) 

the 0.7 is treated as a double. Try 0.7f to ensure the value is treated as a float:

  if(f == 0.7f) 

But as Michael suggested in the comments below you should never test for exact equality of floating-point values.

like image 141
halfdan Avatar answered Sep 23 '22 20:09

halfdan


This answer to complement the existing ones: note that 0.7 is not representable exactly either as a float (or as a double). If it was represented exactly, then there would be no loss of information when converting to float and then back to double, and you wouldn't have this problem.

It could even be argued that there should be a compiler warning for literal floating-point constants that cannot be represented exactly, especially when the standard is so fuzzy regarding whether the rounding will be made at run-time in the mode that has been set as that time or at compile-time in another rounding mode.

All non-integer numbers that can be represented exactly have 5 as their last decimal digit. Unfortunately, the converse is not true: some numbers have 5 as their last decimal digit and cannot be represented exactly. Small integers can all be represented exactly, and division by a power of 2 transforms a number that can be represented into another that can be represented, as long as you do not enter the realm of denormalized numbers.

like image 43
Pascal Cuoq Avatar answered Sep 24 '22 20:09

Pascal Cuoq