0

How come C can represent the floating points 1.75 and 1.05 exactly, but not 2.45 and 0.7?

In the code below I have tried to demonstrate what I mean. 1.75 - 1.05 - 0.70 is exactly 0, but 1.75 - 2.45 - 0.70 is not, but the amount of decimal places is the same.

C code:

  int digs = DECIMAL_DIG;

  printf("1.75 - 1.05 -0.70: %.*e \n",digs, A1-A3-A4);
  printf("1.75 - 2.45 - 0.70: %.*e \n",digs, A1-A2+A4);
  printf("\n2.45: %.*e \n",digs, 2.45);
  printf("\n1.75: %.*e \n",digs, 1.75);
  printf("\n1.05: %.*e \n",digs, 1.05);
  printf("\n0.70: %.*e \n",digs, 0.70);
  printf("\n1.00: %.*e \n",digs, 1.00);

Output:

1.75 - 1.05 -0.70: 0.000000000000000000000e+000
1.75 - 2.45 - 0.70: -2.220446049250313100000e-016

2.45: 2.450000000000000200000e+000

1.75: 1.750000000000000000000e+000

1.05: 1.050000000000000000000e+000

0.70: 6.999999999999999600000e-001

1.00: 1.000000000000000000000e+000
john
  • 395
  • 2
  • 4
  • 13
  • 1
    Write it down not as decimals (base 10) but as binary (base 2) and all will be clear. Seriously. I'm not joking. 1=>1, 2=>10, 0.5 => 0.1, 0.25 => 0.01, but how do does look 0.15 or 0.17 or in binary? Try writing it all, then remember there is a limited number of bits, and try taking what's left and converting it back to decimal. – quetzalcoatl Oct 25 '17 at 21:16
  • 4
    You know the amount of numbers that can be represented using a finite number of bits is also finite? But the amount of fractional numbers between two arbitrary numbers is infinite. – Eugene Sh. Oct 25 '17 at 21:17
  • 2
    Same reason as why some rational numbers can be represented with a terminating decimal (like 1/4 = 0.25), but others cannot (like 1/3 = 0.3333…). –  Oct 25 '17 at 21:20
  • 2
    @quetzalcoatl: you are right, but I guess that many people will have problems expressing floating point values in anything else but decimal. It takes some time and understanding to grasp that binary 0.1 is decimal 0.5, etc. And it gets worse with values like binary 0.1010001 etc. – Rudy Velthuis Oct 26 '17 at 06:49

0 Answers0