简体   繁体   English

为什么乘以N除以“修复”浮点表示?

[英]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.6840.03而这个技巧实际上使它变得更糟。 Or 0.22 and 0.99 . 0.220.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)将数字转换为二进制,您将看到差异:

控制台显示<code> 0.1 </ code>,<code> 0.2 </ code>,<code> 0.1 * 0.2 </ code>和<code>((0.1 *(0.2 * 1000))/ 1000 </ code>每个都带有二进制表示

Correlation does not imply causation. 相关并不意味着因果关系。

由于数字是常量,因此可以在将数字赋给变量之前计算表达式,因此除了存储表达式结果的变量之外,不需要使用浮点变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么进度条显示浮点值? - Why does my progress bar display a floating point value? 在Javascript中,为什么getBoundingClientRect()有时会返回浮点值? - In Javascript, why does getBoundingClientRect() sometimes return floating point values? 为什么浮点误差会根据小数点的位置而变化? - Why does floating point error change based on the position of the decimal? 如何解决NaN错误-参数值不加,减,除或乘-在JavaScript中 - How to Fix NaN Error - Argument Values Not Adding, Subtracting, Dividing, or Multiplying - In JavaScript 为什么JavaScript使用基数为10的浮点数(根据w3schools)? - Why does JavaScript use base 10 floating point numbers (according to w3schools)? 为什么console.log不显示分配的var的IEEE-754浮点值? - Why does console.log not show IEEE-754 floating point value of assigned var? 在Javascript中乘以浮点数时,这是处理舍入错误的可靠方法吗? - Would this be a reliable way to deal with rounding errors when multiplying floating point numbers in Javascript? 浮点数什么时候溢出? - When does a floating point number overflow? 为什么reduce受浮点问题而不是for循环影响? - Why reduce is affected by floating point issue and for loop not? 为什么浮点数的打印方式如此不同? - Why are floating point numbers printed so differently?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM