-5

I have a simple C snippet as follows:

#include<stdio.h>
#include<conio.h>

int main()    
{
    float a=0.3,b=0.5
    clrscr();

    if(a==0.3)
    {
        printf("equal");
    }
    else
    {
        printf("unequal");
    }

    if(b==0.5)
    {
        printf("equal");
    }
    else
    {
        printf("unequal");
    }

    getch();
}

shows output as: unequal equal.

I understand this because computer takes 0.3 as 1/3 and as 0.333... is not equal to 0.33, it shows output unequal, while in 0.5 is precise number so it gives output as equal.

But now if I take float b=0.2 like this:

float b=0.2;
if(b==0.2)
{
    printf("equal");
}
else
{
    printf("unequal");
}

Then it also shows unequal as output! As 0.2 is 1/5 - precise value, it should give output equal.

Can anyone tell me if anything is wrong here?

Krupal Shah
  • 8,949
  • 11
  • 57
  • 93
  • 4
    Read any basic text about floating-point numbers. – Deduplicator Sep 08 '14 at 14:33
  • 2
    "I understand this because computer takes `0.3` as `1/3`": Why should it do so? "and as 0.333... is not equal to 0.33" Where does the 0.33 come from now? – glglgl Sep 08 '14 at 14:37
  • @Deduplicator i searched on the web and found some results about truncation error.but AFAIK, 1/5 does not give any truncation error. – Krupal Shah Sep 08 '14 at 14:37
  • @krupalshah Convert 1/5 to decimal and you'll see that it indeed is truncated as well. But if you take .25, .125, .0625 etc, it is not truncated. – glglgl Sep 08 '14 at 14:55
  • You should use `double` or cast literals to `float` if you absolutely need to make those comparisons with literals, as they are of type `double`. http://codepad.org/RfTDQ9XL – humodz Sep 08 '14 at 15:29
  • `short int x = 65537; if (x == 65537) printf("equal\n");`. – R.. GitHub STOP HELPING ICE Sep 08 '14 at 15:30

1 Answers1

2

Simplifying somewhat, floating point numbers are basically stored as a series of fractions of powers of 2. (1/2, 1/4, 1/8, 1/16, 1/32, 1/64, etc). If your number can be represented as the sum of some number of those, you are lucky -- for most numbers (1/3, 1/5, etc) you get a pretty close approximation. Comparing floating point numbers for exact equality is fraught with peril.

John Hascall
  • 9,176
  • 6
  • 48
  • 72