简体   繁体   English

“Math.round”未正确四舍五入到最接近的整数

[英]"Math.round" is not rounding to the nearest integer correctly

Can someone please kindly explain to me why "Math.round" is not rounding to the nearest integer correctly?有人可以向我解释为什么“Math.round”没有正确四舍五入到最接近的整数吗? I have a 2D array, in which I want to find out the average of each columns.我有一个二维数组,我想在其中找出每列的平均值。

const nums = [[ 20,10,35 ],[70,179,30],[207,223,8],[38,53,52],[234,209,251],[35,94,2]]

After transposing the each columns into rows:将每列转置为行后:

[
  [ 20, 70, 207, 38, 234, 35 ],
  [ 10, 179, 223, 53, 209, 94 ],
  [ 35, 30, 8, 52, 251, 2 ]
]

I was able to return the average to be rounded off.我能够返回要四舍五入的平均值。

const avg = (arr) => arr[0].map((_,i) => arr.reduce((sum,v) => sum + Math.round(v[i]/arr.length),0))

Unfortunately, "Math.round" is not rounding the result correctly:不幸的是,“Math.round”没有正确舍入结果:

before  // [ 100.66666666666667, 127.99999999999999, 63.00000000000001 ]
after   // [ 101, 129, 63 ]

As you can see the 2nd element shoud have rouned off to "128" instead of "129".正如你所看到的,第二个元素应该是“128”而不是“129”。 I've tried testing as followed without problem:我已经尝试过如下测试没有问题:

console.log(Math.round(127.99999999999999)); // 128

However, "Math.round" from my function is outputting incorrect result.但是,我的函数中的“Math.round”输出不正确的结果。 Is this a glitch?这是一个故障吗? Or is there something wrong with my function?还是我的功能有问题? Any feedback will be greatly appreciated, million thanks in advance :)任何反馈将不胜感激,万分感谢提前:)

UPDATE:更新:

Thanks to zer00ne's amazing tip, I was able to refactored the code to make the function work as followed:感谢 zer00ne 的惊人技巧,我能够重构代码以使函数按如下方式工作:

const avg = (arr) => arr[0].map((_,i) => Math.round(arr.reduce((sum,v) => sum + v[i]/arr.length,0)));

console.log(avg(nums)); // [ 101, 128, 63 ]

JavaScript math is at times inaccurate because it stores numbers in memory as binary floats, for details see Why JavaScript is Bad At Math . JavaScript 数学有时不准确,因为它将数字作为二进制浮点数存储在内存中,有关详细信息,请参阅为什么 JavaScript 不擅长数学 Anyways, if you're looking to have an array of three averages see the example below.无论如何,如果您想要一个包含三个平均值的数组,请参见下面的示例。

 const data = [ [ 20, 70, 207, 38, 234, 35 ], [ 10, 179, 223, 53, 209, 94 ], [ 35, 30, 8, 52, 251, 2 ] ]; let output = data.map(sub => Math.round( sub.reduce( (sum, cur) => sum + cur)/sub.length) ); console.log(output);

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

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