[英]Why does multiplying and dividing by N “fix” floating point representation?
I am working in JavaScript, but the problem is generic. 我在使用JavaScript,但问题是通用的。 Take this rounding error:
采取这种舍入错误:
>> 0.1 * 0.2
0.020000000000000004
This StackOverflow answer provides a nice explanation. 这个StackOverflow答案提供了一个很好的解释。 Essentially, certain decimal numbers cannot be represented as precisely in binary.
实质上,某些十进制数不能精确地表示为二进制数。 This is intuitive, since 1/3 has a similar problem in base-10.
这很直观,因为1/3在base-10中有类似的问题。 Now a work around is this:
现在一个解决方法是:
>> (0.1 * (1000*0.2)) / 1000
0.02
My question is how does this work? 我的问题是这是如何工作的?
It doesn't. 它没有。 Try
0.684
and 0.03
instead and this trick actually makes it worse. 尝试
0.684
和0.03
而这个技巧实际上使它变得更糟。 Or 0.22
and 0.99
. 或
0.22
和0.99
。 Or a huge number of other things. 或者其他很多东西。
It doesn't work. 它不起作用。 What you see there is not exactly
0.02
, but a number that is close enough (to 15 significant decimal digits) to look like it. 你看到的不完全是
0.02
,而是一个足够接近(15个有效十进制数字)的数字。
It just happens that multiplying an operand by 1000, then dividing the result by 1000, results in rounding errors that yield an apparently "correct" result. 只是将操作数乘以1000,然后将结果除以1000,会导致舍入错误,从而产生明显“正确”的结果。
You can see the effect for yourself in your browser's Console. 您可以在浏览器的控制台中看到自己的效果。 Convert numbers to binary using
Number.toString(2)
and you'll see the difference: 使用
Number.toString(2)
将数字转换为二进制,您将看到差异:
Correlation does not imply causation. 相关并不意味着因果关系。
由于数字是常量,因此可以在将数字赋给变量之前计算表达式,因此除了存储表达式结果的变量之外,不需要使用浮点变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.