Knowledge about

System + Comprehensive

First of all, 0.1 + 0.2 is not equal to 0.3, because floating point numbers represent decimals with a loss of accuracy.

As we said yesterday, javascript uses 52 bits to represent fractional parts.

According to the international standard IEEE 754, 64 binary bits of JavaScript floating point numbers.

If you have any questions, please review the previous one by yourself.

Here’s why floating point numbers don’t represent decimals exactly.

Binary means integer

The decimal system binary 2 ^ 2 2 ^ 1 2 ^ 0
4 2 1
0 0
1 1
2 1 0
3 1 1
4 1 0 0
5 1 0 1

Mod by division by two

Decimal conversion to binary is called

Mod by division by two

In 5, for example

5/2 is 2 with 1 remaining, 2/2 is 1 with 0 remaining, 1/2 is 0 with 1 remainingCopy the code

And you can see from the above equation that you can see very clearly, the remainder is going to be the binary representation of 5.

Conclusion: integers can be represented consecutively as long as there are enough bits

Binary representation of decimal

The decimal system binary 2 ^ – 2 2 ^ 1
0.25 0.5
0 0
0.5 1
0.25 1 0
0.75 1 1

You can see that the accuracy gets better and better as you use more bits of binary but like 1/5 and 1/10 is never going to be represented

Multiplication and rounding

Let’s start with 0.75

0.75 * 2 = 1.5 round up 1, leaving 0.5. 0.5 * 2 = 1 round up 1, leaving 0Copy the code

Are all integer parts joined up to be exactly the binary part of 0.75

Let’s move on to the miserable 0.1

0.1 * 2 = 0.2 rounded 0, 0.2 * 2 = 0.4 rounded 0, 0.4 * 2 = 0.8 rounded 0, 0.8 0.8 * 2 = 1.6 rounded 1, 0.6 0.6 * 2 = 1.2 rounded 0 1 left 0.2 0.2 * 2 = 0.4 rounded 0 left 0.4 0.4 * 2 = 0.8 rounded 0 left 0.8 0.8 * 2 = 1.6 rounded 1 left 0.6 0.6 * 2 = 1.2 rounded 1 left 0.2..... I went to BaBQ and I felt like I couldn't finishCopy the code

In fact, the same 0.2 you can try

So you can’t take 1/5 and 1/10 with finite precision.

It’s like a fool cutting a watermelon half at a time, but he can’t cut you a fifth anyway.

So a finite number of 52 bits cannot represent a number like 0.1 and the only way to do that is by interception.

So you get the idea.

The interview guide

Refining + system + self-consistency

  • Basic concept: Number is a floating point Number, indicating that decimals have a loss of precision.
  • Progressive: Floating point numbers represent rules.

review

  • The little Red book has mentioned the super classic question, also not necessarily all people can answer well.

    • Primary: Number is a floating point Number, indicating that decimals have a loss of precision.
    • Intermediate: Representation rules for floating point numbers
    • Advanced: High precision computation, language and solution suitable for high precision