1
float x=1.1;

if(x==1.1) //This condition evaluates to false, since a float is being compared to a double.

float x=1.25;

if(x==1.25) //This condition evaluates to true, since 1.25 is not a recurring binary number.

However, I want to know how a float and a double are actually compared?

Is the float promoted to a double (by adding leading 0s) and then compared?

unwind
  • 391,730
  • 64
  • 469
  • 606
user2684198
  • 812
  • 1
  • 10
  • 18

2 Answers2

6

First, you should never compare floating-point numbers for exact equality, since it has a high risk of failing. As always, see WECSSKAFPA.

It's better to compute the absolute distance between the numbers, and compare that to some threshold.

To answer your second question, yes, the float is promoted to double, but of course that can't add actual digits which are missing from the float to begin with. Also the promotion doesn't happen by "adding leading 0s", see the binary representations of float vs double for details.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Can you tell me what you mean by compute the absolute distance between the numbers and compare that to some threshold? Also, if not by adding leading 0s, how is a float promoted to a double? – user2684198 Apr 01 '14 at 15:18
  • Depending on exactly what you are dealing with, the quotient might be better than the difference: `x = 9.98E+42; y = 9.99E+42;` – pmg Apr 01 '14 at 15:19
  • @user2684198: To compare float a and float b, calculate the difference `diff=(a-b)`, take the absolute value of it (`if(diff < 0) diff = -diff;` or call some function to do so) and then compare if diff is smaller than something like `0.0001` . Thats because of the property of floating point vars to be unable to do exact calculation. Something which should result in 10 could be 9.9999999 or 10.000001 ... if you compare exactly to 10, it would be not equal. That´s the reason for this complicated comparison method. – deviantfan Apr 01 '14 at 15:59
  • @user2684198: About the promotion: a float or double has 2 (with sign 3) different sections within his 32/64 bit, see wikipedia for details. If you just add leading zeros like with an int, it would not be the same value as before. – deviantfan Apr 01 '14 at 16:02
0

In both cases, the float is promoted to a double. In one case you are getting true by coincidence -- the number is represented exactly by the computer. In the other case, you are getting false because the computer does not represent it exactly.

R Sahu
  • 204,454
  • 14
  • 159
  • 270