Why does multiplication and division by N "fix" the floating point representation?

I work in JavaScript, but the problem is general. Take this rounding error:

>> 0.1 * 0.2
0.020000000000000004

qaru.site/questions/561 / ... it gives a nice explanation. Essentially, some decimal numbers cannot be represented exactly in binary form. This is intuitive, since 1/3 has a similar problem in base-10. Now it works:

>> (0.1 * (1000*0.2)) / 1000
0.02

My question is: how does it work?

+4
source share
3 answers

. , , 0.02, , ( 15 ), .

, 1000, 1000, , , -, "" .

. Number.toString(2), :

Console showing <code> 0.1 </code>, <code> 0.2 </code>, <code> 0.1 * 0.2 </code> and <code> ((0.1 * (0.2 * 1000)) / 1000 </code> each with their binary representations

.

+4

. 0.684 0.03, . 0.22 0.99. .

+4

, , float-, , .

0
source

Source: https://habr.com/ru/post/1544227/


All Articles