3

My code is

void main()
{
    float a = 0.7;
    if (a < 0.7)
        printf("c");
    else
        printf("c++");
} 

It prints C and this is fine as a treated as double constant value and its value will be 0.699999 which is less than 0.7.

Now if I change the value to 0.1,0.2,0.3 till 0.9 in a and also at if condition then it prints C++, apart from 0.7 and 0.9 that mean both are equal or a is greater.

Why this concept not consider for all value?

John
  • 159
  • 11
  • 12
    Read [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/) – pmg Sep 06 '12 at 17:46
  • Does it treat <= with the same diligence for the other way around? (seems so). – Captain Giraffe Sep 06 '12 at 17:48
  • @CaptainGiraffe I didn't check it lemme check this too.. – John Sep 06 '12 at 17:49
  • So @nos why 0.8 shows C++ output – John Sep 06 '12 at 17:50
  • @CaptainGiraffe they are greater when comparing `0.6<=0.6` or `0.8<=0.8` – John Sep 06 '12 at 17:52
  • This is an exact duplicate of [Floating point comparison `a != 0.7`](http://stackoverflow.com/questions/6883306/floating-point-comparison-a-0-7) (which is, by the way, the third hit if you search for 0.7 -- did you try seeing if the question had already been asked?) – Stephen Canon Sep 06 '12 at 17:56
  • @StephenCanon I search but didn't get thanks for help :) – John Sep 06 '12 at 17:59

1 Answers1

11

What "concept" are you talking about?

None of the numbers you mentioned are representable precisely in binary floating-point format (regardless of precision). All of the numbers you mentioned end up having infinite number of binary digits after the dot.

Since neither float nor double have infinite precision, in float and double formats the implementation will represent these values approximately, most likely by a nearest representable binary floating-point value. These approximate values will be different for float and double. And the approximate float value might end up being greater or smaller than the approximate double value. Hence the result you observe.

For example in my implementation, the value of 0.7 is represented as

+6.9999998807907104e-0001 - float
+6.9999999999999995e-0001 - double

Meanwhile the value of 0.1 is represented as

+1.0000000149011611e-0001 - float
+1.0000000000000000e-0001 - double

As you can see, double representation is greater than float representation in the first example, while in the second example it is the other way around. (The above are decimal notations, which are rounded by themselves, but they do have enough precision to illustrate the effect well enough.)

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765