简体   繁体   English

Decimal.js乘法方法无法正常工作

[英]Decimal.js multiplication method does not work propely

I faced the Floating-Point-Precision problem in JavaScript and to solve it i found libraries like Decimal.js or BigNumber.js. 我遇到了JavaScript中的浮点精度问题,为解决这个问题,我发现了诸如Decimal.js或BigNumber.js之类的库。 It was working fine for me until i tried the following. 在我尝试以下操作之前,它对我来说工作正常。

I have a total of 60 and a share of 10. So the percentage of the share is 10/60*100 (16.666666666666666667%). 我总共有60个份额,共有10个份额。因此,份额百分比为10/60 * 100(16.666666666666666667%)。

Now i want to know what 16.666666666666666667% of 360 are which is 60 (calculator) but for some reason i get 60.000000000000000001 with Decimal.js. 现在我想知道360的16.666666666666666667%是60(计算器),但是由于某种原因,我使用Decimal.js得到60.000000000000000001。

var percentage = (Decimal(10).div(60)).mul(100); 
console.log(percentage.toString()); // 16.666666666666666667

var share = (Decimal(360).mul(percentage)).div(100);
console.log(share.toString()); // 60.000000000000000001

I expected to get 60 but got this. 我预计会得到60,但得到了这个。 Am i missing something or it is a problem of the library because im a bit confused that this is not working with a library that was created for such problems. 我是否遗漏了某些东西,或者这是该库的问题,因为我有点困惑,认为这不适用于针对此类问题创建的库。

Your calculator and your library are both rounding. 您的计算器和库都在四舍五入。

The exact result of multiplying 16.666666666666666667 by 60 is 1000.00000000000000002. 16.666666666666666667与60的乘积的精确结果是1000.00000000000000002。 If you multiply 166.66666666666666667 by 6, by hand, you begin with 6*7 = 2 with a carry-out of 4. After that, as you work to the left, you are multiplying 6 * 6 with a carry-in of 4. The result is 0 with a carry-out of 4. Finally 6*1+4 is 0 with a carry-out of 1. 如果用手将166.66666666666666666667乘以6,则从6 * 7 = 2开始,进位为4。此后,在向左工作时,您将6 * 6乘以进位4。结果为0,进位为4。最后6 * 1 + 4为0,进位为1。

What you are missing is that rounding error is not unique to binary floating point. 您缺少的是舍入错误并非二进制浮点独有。 Any radix X fraction representation, including decimal, can only represent exactly rationals whose denominator can be made a power of X. For decimal, X is ten and 1/6 cannot be represented exactly as A/10 B for any pair of integers A and B. 任何基数X分数表示形式(包括十进制)都只能精确表示其分母可以由X的幂表示的有理数。对于十进制,X是十,而对于任何一对整数A和B ,则不能将其精确表示为A / 10 B。 B.

Unless you go to a general rational number library you have to deal with rounding error. 除非您使用一般的有理数库,否则必须处理舍入错误。 Even a library that can represent any rational number, subject only to memory limits, will have to round irrationals, such as most square roots. 即使是可以表示任何有理数的库(仅受内存限制),也必须舍入非理性数,例如大多数平方根。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM