0

I couldn't find any question about this, so I decided to post. Basically, I just noticed that whenever I initialize float or double variables, the actual values assigned are approximations of what I specified.

Ex:

float dx = 7.1; //upon debugging this is: 7.09999990

float dy = 9.9; //upon debugging this is: 9.89999962

I realize that they're approximations of what I asked, and that in a real calculation it's absolutely understood that the result would be a calculation, but I'm wondering and sort of expected the aproximation to be 7.10000000

And also, if I use the constant 7.1 or 7.10000000 in something like if (7.10000000 == 7.1), it seems literal constant is approximated to 7.0999999999999996. (I guess this is a bit obvious now, it's first aproximated to a double and not a float; so this isn't a mystery anymore)

So I guess my question is why is 7.1 approximated to 7.09999990, and not even 7.09999999 which is closer to 7.1 than 7.09999990. No? Am I missing something?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 6
    Here's some reading material: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – 001 Apr 05 '17 at 19:23
  • @JohnnyMopp: Holy mackerel! I suspected it might be sophisticated stuff, but man. Thanks a bunch for the article. I kinda feel sorry I asked. Ignorance is bliss? Not really ... but maybe sometimes. :D – danutz_plusplus Apr 05 '17 at 19:27
  • 1
    Basically, you can't represent some (well, infinitely many) decimal values _exactly_ using binary: these are finite fractions in decimal, but infinite ones in binary, so the computer has to cut them, which results in loss of precision, but you can't really do anything about this. Choose another base (like base-3, then fractions like 1/3 will be exactly representable), and you'll find it that there still are infinitely many values you can't represent exactly. – ForceBru Apr 05 '17 at 19:38
  • The layman's floating point guide http://floating-point-gui.de/ – franji1 Apr 05 '17 at 20:18
  • Much appreciated! Thanks – danutz_plusplus Apr 05 '17 at 20:46
  • Indeed, a duplicate is seems to be. I seem to have missed it when initially searching for a similar question to mine. Thanks for the reference. It's got a lot more information on the subject. – danutz_plusplus Apr 13 '17 at 05:08

0 Answers0