4
int main() {
float a = 20000000;
float b = 1;
float c = a+b;

if (c==a) { printf("equal"); }

else { printf("not equal");}
return 0;
}

when I run this it says "equal". but when I change the value of a to 2000000 (one zero less) the answer is no. why ?

Coding Mash
  • 3,338
  • 5
  • 24
  • 45
wantToLearn
  • 481
  • 4
  • 7
  • 19
  • The mechanism in which a comparatively small value, here 1, disappears completely when added to a large value is called “absorption” in floating-point vocabulary. – Pascal Cuoq Oct 28 '12 at 20:46

4 Answers4

7

Typically, a float has a precision of 24 bits. The number 20000001 = 0x1312d01 needs 25 bits to be represented exactly, so it must be rounded. The normal rounding mode for values exactly half-way between two representable values is rounding to last-bit-zero, hence 20000001 is rounded to 20000000 as a float.

2000001 = 0x1e8481 needs fewer than 24 bits to be represented (21), so there is no rounding needed for that.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • No, 2000000 =0x1e8480. If the last nibble is odd, the number must be odd. – Daniel Fischer Oct 28 '12 at 20:38
  • HOw do you calculate this number 0x1312d01 ? – wantToLearn Oct 28 '12 at 20:46
  • @wantToLearn `printf("%a", 20000000.f);` may be useful—although you may find it confusing when you try `printf("%a", 20000001.f);`. – Pascal Cuoq Oct 28 '12 at 20:50
  • I asked my Haskell interpreter, that's faster than doing it by hand. But doing it by hand is also simple. You determine the bits from least significant to most (right to left), if the number is odd, the last bit is 1, else 0. Divide the number by 2 (discarding the fractional part). Recur until you reach 0. In C, you can print unsigned integers in hexadecimal with the `%x` format. – Daniel Fischer Oct 28 '12 at 20:51
  • 20000002 needs 25 bits as well but it's exactly representable as a float... – Mustafa Aydın Aug 23 '22 at 18:15
3

Floating point numbers are very often approximate values instead of exact values. You can read all about it here:

http://en.wikipedia.org/wiki/Floating_point

1

If you declare two variable as of type float and then even you put those two value same. You would get unpredictable result if you compare for equality. For more details google for IEEE standard (IEEE 754) for representing floating point number. wikipedia article

  • Is it not contradictory to claim that one gets “ unpredictable result if you compare for equality” while linking to a Wikipedia article that explains that floating-point arithmetic was standardized in **1985** for predictability? – Pascal Cuoq Oct 28 '12 at 20:41
  • @PascalCuoq How and why if the article clearly explains that the floating number may be rounded up –  Oct 28 '12 at 20:43