1
#include <stdio.h>
main()
{
    float f = 0.1;
    if (f == 0.1)
        printf("True");
    else
        printf("False");
}

OUTPUT: False

Why does it print False and not True?

herohuyongtao
  • 47,739
  • 25
  • 124
  • 164

4 Answers4

4

You should not use != to check float!

The code is equal to check if (0.1f == 0.1), as promotion and conversion rules mean that the comparison take place between double numbers. The decimal number 0.1 is represented differently as a single-precision float and as a double-precision double (and none of these two representations is exact), so when 0.1f is promoted to double, the result is quite a bit different from the double representing 0.1.

You should use

if (fabs(f-0.1) < 0.001)      // for 0.001, can be other suitable precisions 

P.S.: To read on, check out What Every Computer Scientist Should Know About Floating-Point Arithmetic.

herohuyongtao
  • 47,739
  • 25
  • 124
  • 164
3

Typical floating point does not exactly represent numbers like 0.1 exactly.

0.1 is a double and is only nearly the numeric value 0.1 - see below. Assigning that to a float creates a further reduction in precision.

float f = 0.1;
// Convert 0.1 to a `double`.  closest double is     0.10000000000000000555
// Assigned that double to a float: closest float is 0.10000000149011611938

Finally comparing this to the high precision double version of 0.1 leads to a mis-match.

if (f == 0.1) // does not compare as equal
// compare f which is 0.10000000149011611938 to 
// 0.10000000000000000555 and they are not equal.

Example

volatile float f = 0.1;
printf("%.20f\n", f);
// 0.10000000149011611938
volatile double d = 0.1;
printf("%.20f\n", d);
// 0.10000000000000000555
chux - Reinstate Monica
  • 127,356
  • 13
  • 118
  • 231
1

You may use

if(f-0.1<=accuracy)
sqd
  • 1,403
  • 13
  • 23
1

Do not use (in)equality for floating point numbers - They are stored as imprecise numbers - That is where the floating bit comes in

Write

if (fabsf(f - 0.1) < precision) ...

Where precision is the accuracy you require

See fabs(3) and What Every Computer Scientist Should Know About Floating-Point Arithmetic

Lee Duhem
  • 14,412
  • 3
  • 28
  • 46
Ed Heal
  • 57,599
  • 16
  • 82
  • 120