Comparison of floating and double variables

Possible duplicates:
The difference between float and double
strange conclusion in comparison float with floating literal

I use Visual C ++ 6.0, and in the program I compare float and double variables For example, for this program

#include<stdio.h> int main() { float a = 0.7f; double b = 0.7; printf("%d %d %d",a<b,a>b,a==b); return 0; } 

I get 1 0 0 as output

and for

 #include<stdio.h> int main() { float a = 1.7f; double b = 1.7; printf("%d %d %d",a<b,a>b,a==b); return 0; } 

I get 0 1 0 as output.

Please tell me why I get this strange conclusion and is there a way to predict these outputs on a single processor. Also, how are two variables compared in C?

+4
source share
4 answers

This is due to the way the internal representation of floats and pair numbers is in the computer. Computers store numbers in binary format, which is basic 2. The basic 10 numbers, when stored in a binary file, can have duplicate numbers, and the β€œexact” value stored on the computer does not match.

When you compare floats, epsilon is usually used to indicate a slight change in values. For instance:

 float epsilon = 0.000000001; float a = 0.7; double b = 0.7; if (abs(a - b) < epsilon) // they are close enough to be equal. 
+8
source

1.7d and 1.7f are likely to be different values: one of them is closest to the absolute value of 1.7 in the dual representation, and one of them is closest to the absolute value of 1.7 in the floating-point representation.

To put it in more understandable terms, imagine that you had two types: shortDecimal and longDecimal . shortDecimal is a decimal value with 3 significant digits. longDecimal is a decimal value with 5 significant digits. Now imagine that you have a way of representing pi in a program and assigning a value to the shortDecimal and longDecimal . The short value is 3.14, and the long value is 3.1416. These two values ​​do not match, although they are both the closest representable value for pi in their respective types.

+2
source

1.7 is decimal. In binary form, it has a non-finite representation.

Therefore, 1.7 and 1.7f are different.

Heuristic proof: when you shift bits to the left (i.e., multiply by 2), in the end it will be an integer if the binary representation were "finite".

But in the decimal sequence, multiply 1.7 by 2 and again: you will get only non-integer numbers (the decimal part will cycle between .4 , .8 , .6 and .2 ). Therefore 1.7 is not a sum of powers of 2.

+1
source

You cannot compare floating point variables for equality. The reason is that decimals are represented as binary, which means a loss of precision.

0
source

All Articles