Why 1/3 as double - 0.33333333333333331
The closest way to represent 1/3 in binary format is: 0.010101010101 ... Same as the series 1/4 + (1/4) ^ 2 + (1/4) ^ 3 + (1/4) ^ 4...
Of course, this is limited by the number of bits that you can save in double. A double bit is 64 bits, but one of them is a sign bit, and the other 11 is an exponent (consider it as a scientific designation, but in binary form). So the rest, which is called the mantissa or value, is 52 bits. Suppose you need to run 1, and then use two bits for each subsequent power 1/4. This means that you can store: 1/4 + 1/4 ^ 2 + ... + 1/4 ^ 27 which is 0.33333333333333333331
Why multiply by 3 rounds by 1
So 1/3, represented in binary format and limited by the size of the binary file: 0.01010101010101010101010101010101010101010101010101010101010101 I do not say that it is stored. As I said, you store bits starting at 1, and you use separate bits for the exponent and sign. But I think itβs useful to consider how you actually write it in base 2.
Let adheres to this "mathematical binary" representation and ignore the limits of the size of the double. You do not have to do this, but I find it convenient. If we want to take this approximation for 1/3 and multiply by 3, it will be the same as the bit offset to multiply by 2, and then add what you started with. This gives us 1/3 * 3 = 0.111111111111111111111111111111111111111111111111111111111
But can a double store? No, remember, you can only have 52 bits of the mantissa after the first 1, and this number has 54 units. Therefore, we know that it will be rounded, in this case rounded to 1.
Why for decimal you get 0.999999999999999999999999999999
In decimal form, you get 96 bits to represent an integer, with the extra bits representing an exponent of up to 28 degrees 10. So, although in the end it is all stored as binary, here we work with powers of 10, so it makes sense to think of a number in base 10. 96 bits allow us to express up to 79 228 162 543 494 333, but for representation 1/3 we are going to go with all 3, up to 28 of them, which we can shift to the right of the decimal point: 0.33333333333333333333333333333.
Multiplying this approximation by 1/3 by 3, we get a number that we can accurately represent. This is only 28 9, all shifted to the right of the decimal point: 0.999999999999999999999999999999. Thus, unlike the double, there is no second round of rounding at this point.