0

For the below code, why the value of cellSide is not 0.80000000000000000 but 0.80000000000000004.

/*****Additional info *******
*#define RADIUS 4
*double cellSide = 0.0  ;
*int iCelleParameter=10;
*****************************/

cellSide = 2 * RADIUS / (double)iCelleParameter;
Manish
  • 11
  • 5
  • 1
    It's because 0.8 is not exactly representable. So you get the closest representable value: http://pages.cs.wisc.edu/~rkennedy/exact-float?number=.8 – David Heffernan Mar 02 '16 at 22:08
  • A *must*-read, "What Every Computer Scientist Should Know About Floating-Point Arithmetic" - http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Jim Buck Mar 02 '16 at 22:12
  • Thank you guys !! Now I know why. – Manish Mar 02 '16 at 22:16

1 Answers1

-1

Floats and doubles cannot represent numbers exactly always, so sometimes they are a little off. For money type values, it works, as you can round to the nearest two digits.

For example, if you set a value to 0.1, it may say 0.0999999999 or 0.100000000001 (I'm not sure what it would be exactly, just that it will be off a tiny bit). This is just normal with floats and doubles.

UPDATE: Updated above since it was pointed out my original example of 2.0 can be represented exactly, but that 0.1 was an example of a number that can't be represented exactly.

astrosteve
  • 320
  • 3
  • 11
  • 1
    Nope. 2 is exactly representable. – David Heffernan Mar 02 '16 at 22:05
  • 1
    Your point is right, just your example is a bad choice: Multiples of 2 are exactly those numbers that ARE representable (including 1/2, 1/4, 1/8 and so on). 0.1 would be an example that is not representable. – Anedar Mar 02 '16 at 22:08
  • 1
    Also, if your money values are large enough, even *they* will not represent the exact amounts need. (Hence why using floats/doubles to represent money is A Bad Idea.) – Jim Buck Mar 02 '16 at 22:08
  • @Anedar or, in this case 0.8 – David Heffernan Mar 02 '16 at 22:08
  • Sorry, I didn't know exactly what numbers might not be able to be represented exactly, just that some numbers cannot be. – astrosteve Mar 02 '16 at 22:56