1

I was going through the same question in two different languages. Got different results. Need help to understand why this is happening?

I wrote the same code in python and got a different result than what was expected from C.

Code 1:

{
  float f = 0.1;
  if (f == 0.1)
    printf("YES\n");
  else
    printf("NO\n");
  return 0;
}

Code 2:

f = float()
f = 0.1
if (f == 0.1):
    print("YES")
else:
    print("NO")

Both must give the same output as NO. But only C is giving the expected output while Python is giving the output as YES.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Manish KC
  • 103
  • 1
  • 9
  • 3
    This is why you never compare floats using `==`. – Robert Harvey Aug 18 '19 at 17:16
  • 2
    In your python code, the first line `f = float()` doesn't make `f` be a float in your code. You can remove it and you will get the same result. A case when you would want to use the `float` function is when you have an integer or a string that you want to convert to a float, as in `f=float(1)` or `f=float("0.1")`. – Craig Aug 18 '19 at 17:17

1 Answers1

11

In your C-Code you compare float 0.1 with double 0.1, where the float value is first converted to double, where, due to limited precision this gives 0.10000000149011612 which is not the same value as the double 0.1.

In Python float is the internally the same as double in C. And double 0.1 is the same as double 0.1.

So Python gives the expected output YES and C gives to not so obvious output NO.

Daniel
  • 42,087
  • 4
  • 55
  • 81