preface

Hello everyone, I am Lin Sanxin, with the most easy to understand the most difficult knowledge points is my motto, the basis is advanced premise is my initial mind. There is a problem plaguing front-end engineers: 0.1 + 0.2! = = 0.3

As you probably know, this is because computers store numbers in binary and render them in decimal, so there are errors. But ask yourself further why the binary memory of a computer causes errors, and you may falter…

Decimal to binary

Let’s start by talking about how to convert from decimal to binary. There are three scenarios:

  • 1, the integer
  • 2. Negative integers
  • 3, decimal

The integer

How do integers go from decimal to binary? Remember a formula: mod two, then reverse order, high zero complement. What does that mean? Hold on, I’ll tell you. I’ll take 81 as an example. After all, there was once a man who scored 81 points in a game:

It can be concluded that 1000101 has 7 bits, but the internal representation of the number is fixed length, such as 8 bits, 16 bits and 32 bits, so 7 bits is not enough, and a high level of 0 is needed, that is, 01000101. The specification is written as (81)10 = (01010001).

Negative integer

For negative integers, here’s the rule:

  • Step 1: Convert positive integers to binary
  • Step 2: Take the inverse of binary
  • Step 3: Add 1 to the inverted binary

Take -81 for example:

The decimal

Turn the decimal binary words is this: after the decimal point number multiplied by 2, results, take the results of the integer part (0 or 1), and then the results after the decimal point number multiplied by 2, results, and take the integer part, and then again after the decimal point of the results of several times 2… And so on. Knowing that the decimal part is zero or the number of digits has reached the number of digits. You just have to sort the integers in order.

Let me give you an example, like 0.125:

Let me give you another example, 121.6:

0.1 + 0.2

Back to 0.1 + 0.2

As you can see, 0.1 and 0.2 are converted to binary infinite loops, more than the largest number, so when stored only by two approximation to store them, the natural, when 0.1 + 0.2, the approximation to turn the decimal is certainly approximation, so cause error, the largest digit is determined according to the hard disk memory size, hard disk memory, the greater the commonly so The higher the accuracy.

conclusion

I am Lin Sanxin, an enthusiastic front-end novice programmer. If you progress, like the front end, want to learn the front end, then we can make friends, touch fish ha ha, touch fish, point this –> touch fish boiling point