About the problem of online already has a lot of articles is very comprehensive, but I used to feel when you see these articles at the beginning of extremely complex, can feel much about what the IEEE 754 standard is very big, but when I actually went to see the problem again found that the most important part of the introduction is just cannot use binary to express some of the decimal system and with fractions, If you go through the process you’ll really understand the problem.

The bottom layer of the computer does the calculation for efficiency by converting a number to binary form. You can convert a positive integer to a binary, but it’s a little confusing to ask you to convert a decimal to a binary, so let’s deduce it. Let’s try converting decimal 0.1 to binary, where 0.1 is actually equal to 0.5(1/2) of decimal because two binary 0.1’s add up to a 1.

So what is 0.01 in binary,0.05 in decimal? No, 0.25(1/2*1/2), because two binary 0.01’s add up to 0.1. To derive the value of the number of digits behind the decimal point = 0.5 to the power of digits (the last digit is always half the expression of the previous one), find the nearest digit smaller than decimal 0.1.

Binary 0.001 = decimal 0.125(1/2*1/2*1/2) Binary 0.0001 = decimal 0.0625(1/2^4) Following the previous conclusion that binary 0.00001 = decimal 0.03125,0.03125 + 0.0625 < 1, so the fifth digit is still 1, loop through the above process and you will find that you will never be able to fully express 0.1 in binary form.

You can’t express 0.1 in terms of 1/2 and the sum to the NTH power

0.0001100110011001100110011001100110011001100110011001101... (Infinite loop)Copy the code

The above method can be distilled into the following common way of converting decimal parts to binary through a series of reversals: the original number *2 takes the whole part as the last part of the binary decimal until the decimal part is 0. (You can verify this.) Then you will find that the nine decimal numbers except 0.5,0.1, and 0.9 are all irrational numbers in binary notation

It’s not a very good idea to have an infinite number of digits behind the decimal point, because it takes up a lot of space, so you have to follow a standard, and when you’re dealing with a binary irrational number like this, you just have to specify which digit to go to.

Then we can discover the root cause of the loss of accuracy. JS standard IEEE 754 appears naturally here, here we only need to know its interception of length, the rest of the extended standard and solution can refer to the community leaders excellent articles and Wikipedia.

Juejin. Cn/post / 684490…

www.cnblogs.com/fsjohnhuang…