Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1
The reason is the limited amount of space to store the digits. The float and double type in C/C++ adhere to the IEEE754 standard for encoding floating point values in memory. For a float, a 32bit floating point type, there are 32bits available. 1 is reserved for the sign, 8 are reserved for the exponent, which leaves 23 bits for the mantissa. I cannot go too deep into all of this. Suffice it to say that floating point numbers are stored in the form 1.m, the leading 1bit is left of the radix point, everything after the radix point is the mantissa (23 bits in length). The leading 1 is not stored, since it is always there. Looking at 713.166, we have 713 = 0b1011001001, that is a leading 1 and 9 bits (011001001). That leaves room for 14 bits of the fractional part 0.166. That is in binary 0b0.00101010011111(...). The ellipsis indicates that there are more binary digits in 0.166 than I have displayed. I only displayed the first 14 bits, since all others will be lost anyway. And that is the key! The limited amount of space forces us to drop digits and thus lose precision. In fact, after the five 1s at the end, I am sure there is another 1. So, actually, the result may be rounded to the stored value 713.166 - m 01100100100101010100000, - sign 0, and - exponent 9 (actually biased). To subtract 713 - m 011001001000000000000000 - sign 0, and - exponent 9 (biased) We end up with 0.00101010100...0, brought back to normal form with leading 1: 1.0101010...0, exponent -3. So, the result is 1.328125. Shifting by exponent -3: 1.328125 * 2^(-3) = 0.166015625, or rounded to (I think the standard) 6 decimal C++ cout format (if nothing else is specified), 0.166016. This was surely very quick, I'd like to ask you to think about it for a minute, read about the IEEE754, learn fractional numbers in binary notation (base 2), and addition/subtraction with binary numbers in mantissa, exponent notation, before you head into a lot of questions I can imagine that you have.
28th Jan 2022, 1:12 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar